From f278895908e663a6a5a2c1f63e5523c5004f5d20 Mon Sep 17 00:00:00 2001 From: weidai Date: Fri, 4 Jul 2003 00:17:37 +0000 Subject: [PATCH] create DLL version, fix GetNextIV() bug in CTR and OFB modes --- 3way.h | 6 +- Readme.txt | 16 +- aes.h | 2 +- algebra.h | 6 + algparam.cpp | 5 + algparam.h | 4 +- arc4.h | 12 +- asn.cpp | 5 + asn.h | 46 ++--- basecode.cpp | 5 + basecode.h | 6 +- blowfish.h | 6 +- camellia.h | 6 +- cast.h | 12 +- cbcmac.cpp | 63 ++++++ cbcmac.h | 75 ++----- channels.cpp | 7 +- channels.h | 2 +- config.h | 38 +++- cryptdll.dsp | 545 +++++++++++++++++++++++++++++++++++++++++++++++++++ cryptest.dsp | 26 +-- cryptest.dsw | 46 +++++ cryptlib.cpp | 7 +- cryptlib.dsp | 29 ++- cryptlib.h | 141 +++++++------ cryptopp.rc | 109 +++++++++++ des.cpp | 4 + des.h | 30 +-- dessp.cpp | 5 + dh.cpp | 5 + dh.h | 2 + diamond.h | 12 +- dll.cpp | 100 ++++++++++ dll.h | 64 ++++++ dlltest.cpp | 178 +++++++++++++++++ dlltest.dsp | 90 +++++++++ dmac.h | 2 +- dsa.cpp | 5 + ec2n.cpp | 8 +- ec2n.h | 12 +- eccrypto.cpp | 21 +- eccrypto.h | 28 ++- ecp.cpp | 17 +- ecp.h | 18 +- eprecomp.cpp | 5 + files.cpp | 21 +- files.h | 10 +- filters.cpp | 9 +- filters.h | 68 +++---- fips140.cpp | 7 +- fips140.h | 20 +- fipstest.cpp | 231 ++++++++++++++-------- gf2n.cpp | 13 +- gf2n.h | 15 +- gfpcrypt.cpp | 5 + gfpcrypt.h | 25 ++- gost.h | 6 +- haval.cpp | 9 +- haval.h | 2 +- hex.cpp | 5 + hex.h | 4 +- hmac.cpp | 84 ++++++++ hmac.h | 105 +++------- idea.h | 6 +- integer.cpp | 17 +- integer.h | 15 +- iterhash.cpp | 20 +- iterhash.h | 58 +++--- lubyrack.h | 6 +- luc.cpp | 2 - mars.h | 6 +- md4.cpp | 10 +- md4.h | 8 +- md5.cpp | 10 +- md5.h | 8 +- md5mac.h | 7 +- mdc.h | 4 +- misc.cpp | 13 +- misc.h | 23 ++- modarith.h | 11 +- modes.cpp | 33 ++-- modes.h | 105 ++++++---- modexppc.cpp | 10 +- modexppc.h | 2 + mqueue.cpp | 5 + mqueue.h | 4 +- nbtheory.cpp | 5 + nbtheory.h | 58 +++--- oaep.h | 3 + osrng.cpp | 5 + osrng.h | 17 +- panama.cpp | 2 +- panama.h | 8 +- pkcspad.cpp | 8 +- pkcspad.h | 15 +- pubkey.cpp | 5 + pubkey.h | 41 ++-- queue.cpp | 5 + queue.h | 4 +- rabin.cpp | 2 - randpool.cpp | 5 + randpool.h | 2 +- rc2.h | 6 +- rc5.h | 6 +- rc6.h | 6 +- rdtables.cpp | 5 + resource.h | 15 ++ rijndael.cpp | 5 + rijndael.h | 14 +- ripemd.cpp | 62 +++--- ripemd.h | 32 +-- rng.cpp | 5 + rng.h | 4 +- rsa.cpp | 12 +- rsa.h | 6 +- safer.h | 16 +- seal.h | 2 +- secblock.h | 20 +- seckey.h | 54 ++--- serpent.h | 6 +- sha.cpp | 77 ++++---- sha.h | 32 +-- shacal2.h | 6 +- shark.h | 6 +- simple.cpp | 19 +- simple.h | 26 +-- skipjack.cpp | 5 + skipjack.h | 12 +- square.h | 6 +- stdcpp.h | 31 +++ strciphr.cpp | 5 + strciphr.h | 30 ++- tea.h | 6 +- test.cpp | 270 +++++++------------------ tiger.cpp | 8 +- tiger.h | 7 +- trdlocal.cpp | 6 + trdlocal.h | 5 +- ttmac.h | 6 +- twofish.h | 6 +- wake.h | 6 +- whrlpool.cpp | 6 +- whrlpool.h | 8 +- xormac.h | 12 +- 144 files changed, 2680 insertions(+), 1235 deletions(-) create mode 100644 cbcmac.cpp create mode 100644 cryptdll.dsp create mode 100644 cryptopp.rc create mode 100644 dll.cpp create mode 100644 dll.h create mode 100644 dlltest.cpp create mode 100644 dlltest.dsp create mode 100644 hmac.cpp create mode 100644 resource.h create mode 100644 stdcpp.h diff --git a/3way.h b/3way.h index 2192eb40..6c6a128a 100644 --- a/3way.h +++ b/3way.h @@ -17,7 +17,7 @@ struct ThreeWay_Info : public FixedBlockSize<12>, public FixedKeyLength<12>, pub /// 3-Way class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *key, unsigned int length, unsigned int rounds); @@ -40,8 +40,8 @@ class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef ThreeWay::Encryption ThreeWayEncryption; diff --git a/Readme.txt b/Readme.txt index d9ca490d..8b11b3e5 100644 --- a/Readme.txt +++ b/Readme.txt @@ -1,5 +1,5 @@ Crypto++: a C++ Class Library of Cryptographic Primitives -Version 5.1 3/20/2003 +Version 5.0 9/11/2002 This library includes: @@ -238,9 +238,15 @@ History - fixed a bug in HMAC::TruncatedFinal() - fixed SKIPJACK byte ordering following NIST clarification dated 5/9/02 -5.01 (special FIPS 140-2 release, in development) - - added known answer test for X9.17 RNG in FIPS 140 power-up self test - - is being evaluated for FIPS 140-2 compliance +5.01 - added known answer test for X9.17 RNG in FIPS 140 power-up self test + - submitted to NIST/CSE, but not publicly released + +5.02 - changed EDC test to MAC integrity check using HMAC/SHA1 + - improved performance of integrity check + - added blinding to defend against RSA timing attack + +5.03 - created DLL version of Crypto++ for FIPS 140-2 validation + - fixed vulnerabilities in GetNextIV for CTR and OFB modes 5.1 - added PSS padding and changed PSSR to track IEEE P1363a draft standard - added blinding for RSA and Rabin to defend against timing attacks @@ -253,3 +259,5 @@ History signature scheme (these fixes are not backwards compatible) - fixed a number of compiler warnings, minor bugs, and portability problems - removed Sapphire + +5.2 - Merged in changes for 5.01 - 5.03 diff --git a/aes.h b/aes.h index ba93d10e..8ec4b8bd 100644 --- a/aes.h +++ b/aes.h @@ -11,7 +11,7 @@ NAMESPACE_BEGIN(CryptoPP) #ifdef CRYPTOPP_DOXYGEN_PROCESSING // Use inheritance instead of typedef to get a seperate API reference page for AES //! AES -class AES : public Rijndael, public BlockCipherDocumentation {}; +class AES : public Rijndael {}; #else typedef Rijndael AES; #endif diff --git a/algebra.h b/algebra.h index a9c677ec..498d5206 100644 --- a/algebra.h +++ b/algebra.h @@ -207,6 +207,9 @@ public: void DivisionAlgorithm(Element &r, Element &q, const Element &a, const Element &d) const {Element::Divide(r, q, a, d);} + bool operator==(const EuclideanDomainOf &rhs) const + {return true;} + private: mutable Element result; }; @@ -265,6 +268,9 @@ public: const Element& MultiplicativeInverse(const Element &a) const; + bool operator==(const QuotientRing &rhs) const + {return m_domain == rhs.m_domain && m_modulus == rhs.m_modulus;} + protected: EuclideanDomain m_domain; Element m_modulus; diff --git a/algparam.cpp b/algparam.cpp index 1f49db6f..268584fd 100644 --- a/algparam.cpp +++ b/algparam.cpp @@ -1,6 +1,9 @@ // algparam.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "algparam.h" NAMESPACE_BEGIN(CryptoPP) @@ -8,3 +11,5 @@ NAMESPACE_BEGIN(CryptoPP) bool (*AssignIntToInteger)(const std::type_info &valueType, void *pInteger, const void *pInt) = NULL; NAMESPACE_END + +#endif diff --git a/algparam.h b/algparam.h index 999998d8..a72af79f 100644 --- a/algparam.h +++ b/algparam.h @@ -243,9 +243,9 @@ AssignFromHelperClass AssignFromHelper(T *pObject, const NameValuePairs &s // ******************************************************** // This should allow the linker to discard Integer code if not needed. -extern bool (*AssignIntToInteger)(const std::type_info &valueType, void *pInteger, const void *pInt); +CRYPTOPP_DLL extern bool (*AssignIntToInteger)(const std::type_info &valueType, void *pInteger, const void *pInt); -const std::type_info & IntegerTypeId(); +CRYPTOPP_DLL const std::type_info & IntegerTypeId(); template class AlgorithmParameters : public NameValuePairs diff --git a/arc4.h b/arc4.h index 7d592bae..0072a78a 100644 --- a/arc4.h +++ b/arc4.h @@ -23,8 +23,8 @@ public: bool IsSelfInverting() const {return true;} bool IsForwardTransformation() const {return true;} - typedef SymmetricCipherFinalTemplate Encryption; - typedef SymmetricCipherFinalTemplate Decryption; + typedef SymmetricCipherFinal Encryption; + typedef SymmetricCipherFinal Decryption; protected: void UncheckedSetKey(const NameValuePairs ¶ms, const byte *key, unsigned int length, const byte *iv); @@ -35,7 +35,7 @@ protected: }; //! . -typedef SymmetricCipherFinalTemplate ARC4; +typedef SymmetricCipherFinal ARC4; //! Modified ARC4: it discards the first 256 bytes of keystream which may be weaker than the rest /*! Use #MARC4 typedef rather than this class directly. */ @@ -44,15 +44,15 @@ class CRYPTOPP_NO_VTABLE MARC4_Base : public ARC4_Base public: static const char *StaticAlgorithmName() {return "MARC4";} - typedef SymmetricCipherFinalTemplate Encryption; - typedef SymmetricCipherFinalTemplate Decryption; + typedef SymmetricCipherFinal Encryption; + typedef SymmetricCipherFinal Decryption; protected: unsigned int GetDefaultDiscardBytes() const {return 256;} }; //! . -typedef SymmetricCipherFinalTemplate MARC4; +typedef SymmetricCipherFinal MARC4; NAMESPACE_END diff --git a/asn.cpp b/asn.cpp index 262a4304..41211ce2 100644 --- a/asn.cpp +++ b/asn.cpp @@ -1,6 +1,9 @@ // asn.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "asn.h" #include @@ -554,3 +557,5 @@ void PKCS8PrivateKey::DEREncode(BufferedTransformation &bt) const } NAMESPACE_END + +#endif diff --git a/asn.h b/asn.h index b3fba6ac..ff91f86e 100644 --- a/asn.h +++ b/asn.h @@ -48,7 +48,7 @@ enum ASNIdFlag inline void BERDecodeError() {throw BERDecodeErr();} -class UnknownOID : public BERDecodeErr +class CRYPTOPP_DLL UnknownOID : public BERDecodeErr { public: UnknownOID() : BERDecodeErr("BER decode error: unknown object identifier") {} @@ -56,27 +56,27 @@ public: }; // unsigned int DERLengthEncode(unsigned int length, byte *output=0); -unsigned int DERLengthEncode(BufferedTransformation &out, unsigned int length); +CRYPTOPP_DLL unsigned int DERLengthEncode(BufferedTransformation &out, unsigned int length); // returns false if indefinite length -bool BERLengthDecode(BufferedTransformation &in, unsigned int &length); +CRYPTOPP_DLL bool BERLengthDecode(BufferedTransformation &in, unsigned int &length); -void DEREncodeNull(BufferedTransformation &out); -void BERDecodeNull(BufferedTransformation &in); +CRYPTOPP_DLL void DEREncodeNull(BufferedTransformation &out); +CRYPTOPP_DLL void BERDecodeNull(BufferedTransformation &in); -unsigned int DEREncodeOctetString(BufferedTransformation &out, const byte *str, unsigned int strLen); -unsigned int DEREncodeOctetString(BufferedTransformation &out, const SecByteBlock &str); -unsigned int BERDecodeOctetString(BufferedTransformation &in, SecByteBlock &str); -unsigned int BERDecodeOctetString(BufferedTransformation &in, BufferedTransformation &str); +CRYPTOPP_DLL unsigned int DEREncodeOctetString(BufferedTransformation &out, const byte *str, unsigned int strLen); +CRYPTOPP_DLL unsigned int DEREncodeOctetString(BufferedTransformation &out, const SecByteBlock &str); +CRYPTOPP_DLL unsigned int BERDecodeOctetString(BufferedTransformation &in, SecByteBlock &str); +CRYPTOPP_DLL unsigned int BERDecodeOctetString(BufferedTransformation &in, BufferedTransformation &str); // for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING -unsigned int DEREncodeTextString(BufferedTransformation &out, const std::string &str, byte asnTag); -unsigned int BERDecodeTextString(BufferedTransformation &in, std::string &str, byte asnTag); +CRYPTOPP_DLL unsigned int DEREncodeTextString(BufferedTransformation &out, const std::string &str, byte asnTag); +CRYPTOPP_DLL unsigned int BERDecodeTextString(BufferedTransformation &in, std::string &str, byte asnTag); -unsigned int DEREncodeBitString(BufferedTransformation &out, const byte *str, unsigned int strLen, unsigned int unusedBits=0); -unsigned int BERDecodeBitString(BufferedTransformation &in, SecByteBlock &str, unsigned int &unusedBits); +CRYPTOPP_DLL unsigned int DEREncodeBitString(BufferedTransformation &out, const byte *str, unsigned int strLen, unsigned int unusedBits=0); +CRYPTOPP_DLL unsigned int BERDecodeBitString(BufferedTransformation &in, SecByteBlock &str, unsigned int &unusedBits); //! Object Identifier -class OID +class CRYPTOPP_DLL OID { public: OID() {} @@ -122,7 +122,7 @@ private: }; //! BER General Decoder -class BERGeneralDecoder : public Store +class CRYPTOPP_DLL BERGeneralDecoder : public Store { public: explicit BERGeneralDecoder(BufferedTransformation &inQueue, byte asnTag); @@ -152,7 +152,7 @@ private: }; //! DER General Encoder -class DERGeneralEncoder : public ByteQueue +class CRYPTOPP_DLL DERGeneralEncoder : public ByteQueue { public: explicit DERGeneralEncoder(BufferedTransformation &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED); @@ -170,7 +170,7 @@ private: }; //! BER Sequence Decoder -class BERSequenceDecoder : public BERGeneralDecoder +class CRYPTOPP_DLL BERSequenceDecoder : public BERGeneralDecoder { public: explicit BERSequenceDecoder(BufferedTransformation &inQueue, byte asnTag = SEQUENCE | CONSTRUCTED) @@ -180,7 +180,7 @@ public: }; //! DER Sequence Encoder -class DERSequenceEncoder : public DERGeneralEncoder +class CRYPTOPP_DLL DERSequenceEncoder : public DERGeneralEncoder { public: explicit DERSequenceEncoder(BufferedTransformation &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED) @@ -190,7 +190,7 @@ public: }; //! BER Set Decoder -class BERSetDecoder : public BERGeneralDecoder +class CRYPTOPP_DLL BERSetDecoder : public BERGeneralDecoder { public: explicit BERSetDecoder(BufferedTransformation &inQueue, byte asnTag = SET | CONSTRUCTED) @@ -200,7 +200,7 @@ public: }; //! DER Set Encoder -class DERSetEncoder : public DERGeneralEncoder +class CRYPTOPP_DLL DERSetEncoder : public DERGeneralEncoder { public: explicit DERSetEncoder(BufferedTransformation &outQueue, byte asnTag = SET | CONSTRUCTED) @@ -227,7 +227,7 @@ public: }; //! . -class ASN1Key : public ASN1CryptoMaterial +class CRYPTOPP_DLL ASN1Key : public ASN1CryptoMaterial { public: virtual OID GetAlgorithmID() const =0; @@ -245,7 +245,7 @@ public: }; //! encodes/decodes subjectPublicKeyInfo -class X509PublicKey : virtual public ASN1Key, public PublicKey +class CRYPTOPP_DLL X509PublicKey : virtual public ASN1Key, public PublicKey { public: void BERDecode(BufferedTransformation &bt); @@ -253,7 +253,7 @@ public: }; //! encodes/decodes privateKeyInfo -class PKCS8PrivateKey : virtual public ASN1Key, public PrivateKey +class CRYPTOPP_DLL PKCS8PrivateKey : virtual public ASN1Key, public PrivateKey { public: void BERDecode(BufferedTransformation &bt); diff --git a/basecode.cpp b/basecode.cpp index 8fe41bec..f37e112b 100644 --- a/basecode.cpp +++ b/basecode.cpp @@ -1,6 +1,9 @@ // basecode.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "basecode.h" #include "fltrimpl.h" #include @@ -229,3 +232,5 @@ unsigned int Grouper::Put2(const byte *begin, unsigned int length, int messageEn } NAMESPACE_END + +#endif diff --git a/basecode.h b/basecode.h index 9d6164f3..b2e53b6a 100644 --- a/basecode.h +++ b/basecode.h @@ -6,7 +6,7 @@ NAMESPACE_BEGIN(CryptoPP) -class BaseN_Encoder : public Unflushable +class CRYPTOPP_DLL BaseN_Encoder : public Unflushable { public: BaseN_Encoder(BufferedTransformation *attachment=NULL) @@ -31,7 +31,7 @@ private: SecByteBlock m_outBuf; }; -class BaseN_Decoder : public Unflushable +class CRYPTOPP_DLL BaseN_Decoder : public Unflushable { public: BaseN_Decoder(BufferedTransformation *attachment=NULL) @@ -55,7 +55,7 @@ private: SecByteBlock m_outBuf; }; -class Grouper : public Bufferless +class CRYPTOPP_DLL Grouper : public Bufferless { public: Grouper(BufferedTransformation *attachment=NULL) diff --git a/blowfish.h b/blowfish.h index dc45a5f7..f5f1c0ac 100644 --- a/blowfish.h +++ b/blowfish.h @@ -16,7 +16,7 @@ struct Blowfish_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 1, //! Blowfish class Blowfish : public Blowfish_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; @@ -33,8 +33,8 @@ class Blowfish : public Blowfish_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Blowfish::Encryption BlowfishEncryption; diff --git a/camellia.h b/camellia.h index 1b43e1de..9d902d91 100644 --- a/camellia.h +++ b/camellia.h @@ -21,7 +21,7 @@ struct Camellia_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 1 /// Camellia class Camellia : public Camellia_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int keylen); @@ -41,8 +41,8 @@ class Camellia : public Camellia_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Camellia::Encryption CamelliaEncryption; diff --git a/cast.h b/cast.h index af66d005..e463bd2c 100644 --- a/cast.h +++ b/cast.h @@ -24,7 +24,7 @@ struct CAST128_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 5, /// CAST-128 class CAST128 : public CAST128_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -47,8 +47,8 @@ class CAST128 : public CAST128_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; //! . @@ -60,7 +60,7 @@ struct CAST256_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16 //! CAST-256 class CAST256 : public CAST256_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length = 8); @@ -76,8 +76,8 @@ class CAST256 : public CAST256_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef CAST128::Encryption CAST128Encryption; diff --git a/cbcmac.cpp b/cbcmac.cpp new file mode 100644 index 00000000..cc0a9939 --- /dev/null +++ b/cbcmac.cpp @@ -0,0 +1,63 @@ +#include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + +#include "cbcmac.h" + +NAMESPACE_BEGIN(CryptoPP) + +void CBC_MAC_Base::CheckedSetKey(void *, Empty empty, const byte *key, unsigned int length, const NameValuePairs ¶ms) +{ + AccessCipher().SetKey(key, length, params); + m_reg.CleanNew(AccessCipher().BlockSize()); + m_counter = 0; +} + +void CBC_MAC_Base::Update(const byte *input, unsigned int length) +{ + unsigned int blockSize = AccessCipher().BlockSize(); + + while (m_counter && length) + { + m_reg[m_counter++] ^= *input++; + if (m_counter == blockSize) + ProcessBuf(); + length--; + } + + while (length >= blockSize) + { + xorbuf(m_reg, input, blockSize); + ProcessBuf(); + input += blockSize; + length -= blockSize; + } + + while (length--) + { + m_reg[m_counter++] ^= *input++; + if (m_counter == blockSize) + ProcessBuf(); + } +} + +void CBC_MAC_Base::TruncatedFinal(byte *mac, unsigned int size) +{ + ThrowIfInvalidTruncatedSize(size); + + if (m_counter) + ProcessBuf(); + + memcpy(mac, m_reg, size); + memset(m_reg, 0, AccessCipher().BlockSize()); +} + +void CBC_MAC_Base::ProcessBuf() +{ + AccessCipher().ProcessBlock(m_reg); + m_counter = 0; +} + +NAMESPACE_END + +#endif diff --git a/cbcmac.h b/cbcmac.h index 7f88e912..b15c7287 100644 --- a/cbcmac.h +++ b/cbcmac.h @@ -6,22 +6,21 @@ NAMESPACE_BEGIN(CryptoPP) -template -class CRYPTOPP_NO_VTABLE CBC_MAC_Base : public SameKeyLengthAs, public MessageAuthenticationCode +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_MAC_Base : public MessageAuthenticationCode { public: - static std::string StaticAlgorithmName() {return std::string("CBC-MAC(") + T::StaticAlgorithmName() + ")";} - CBC_MAC_Base() {} void CheckedSetKey(void *, Empty empty, const byte *key, unsigned int length, const NameValuePairs ¶ms); void Update(const byte *input, unsigned int length); void TruncatedFinal(byte *mac, unsigned int size); - unsigned int DigestSize() const {return m_cipher.BlockSize();} + unsigned int DigestSize() const {return const_cast(this)->AccessCipher().BlockSize();} + +protected: + virtual BlockCipher & AccessCipher() =0; private: void ProcessBuf(); - typename T::Encryption m_cipher; SecByteBlock m_reg; unsigned int m_counter; }; @@ -32,68 +31,20 @@ private: messages use DMAC. */ template -class CBC_MAC : public MessageAuthenticationCodeTemplate > +class CBC_MAC : public MessageAuthenticationCodeImpl >, public SameKeyLengthAs { public: CBC_MAC() {} - CBC_MAC(const byte *key, unsigned int length=CBC_MAC_Base::DEFAULT_KEYLENGTH) + CBC_MAC(const byte *key, unsigned int length=DEFAULT_KEYLENGTH) {SetKey(key, length);} + + static std::string StaticAlgorithmName() {return std::string("CBC-MAC(") + T::StaticAlgorithmName() + ")";} + +private: + BlockCipher & AccessCipher() {return m_cipher;} + typename T::Encryption m_cipher; }; -template -void CBC_MAC_Base::CheckedSetKey(void *, Empty empty, const byte *key, unsigned int length, const NameValuePairs ¶ms) -{ - m_cipher.SetKey(key, length, params); - m_reg.CleanNew(m_cipher.BlockSize()); - m_counter = 0; -} - -template -void CBC_MAC_Base::Update(const byte *input, unsigned int length) -{ - while (m_counter && length) - { - m_reg[m_counter++] ^= *input++; - if (m_counter == T::BLOCKSIZE) - ProcessBuf(); - length--; - } - - while (length >= T::BLOCKSIZE) - { - xorbuf(m_reg, input, T::BLOCKSIZE); - ProcessBuf(); - input += T::BLOCKSIZE; - length -= T::BLOCKSIZE; - } - - while (length--) - { - m_reg[m_counter++] ^= *input++; - if (m_counter == T::BLOCKSIZE) - ProcessBuf(); - } -} - -template -void CBC_MAC_Base::TruncatedFinal(byte *mac, unsigned int size) -{ - ThrowIfInvalidTruncatedSize(size); - - if (m_counter) - ProcessBuf(); - - memcpy(mac, m_reg, size); - memset(m_reg, 0, T::BLOCKSIZE); -} - -template -void CBC_MAC_Base::ProcessBuf() -{ - m_cipher.ProcessBlock(m_reg); - m_counter = 0; -} - NAMESPACE_END #endif diff --git a/channels.cpp b/channels.cpp index 7bb31dd9..8cc3f6e9 100644 --- a/channels.cpp +++ b/channels.cpp @@ -1,6 +1,9 @@ // channels.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "channels.h" NAMESPACE_BEGIN(CryptoPP) @@ -151,7 +154,7 @@ unsigned int ChannelSwitch::ChannelPut2(const std::string &channel, const byte * while (!m_it.End()) { - WasBlocked: +WasBlocked: if (m_it.Destination().ChannelPut2(m_it.Channel(), begin, length, messageEnd, blocking)) { m_blocked = true; @@ -311,3 +314,5 @@ void ChannelSwitch::RemoveRoute(const std::string &inChannel, BufferedTransforma } NAMESPACE_END + +#endif diff --git a/channels.h b/channels.h index cc9aa66e..1ff80a29 100644 --- a/channels.h +++ b/channels.h @@ -77,7 +77,7 @@ public: }; //! Route input to different and/or multiple channels based on channel ID -class ChannelSwitch : public Multichannel, public ChannelSwitchTypedefs +class CRYPTOPP_DLL ChannelSwitch : public Multichannel, public ChannelSwitchTypedefs { public: ChannelSwitch() : m_it(*this), m_blocked(false) {} diff --git a/config.h b/config.h index d82d9f5e..3b864cac 100644 --- a/config.h +++ b/config.h @@ -100,11 +100,7 @@ typedef unsigned char byte; // moved outside namespace for Borland C++Builde NAMESPACE_BEGIN(CryptoPP) typedef unsigned short word16; -#if defined(__alpha) && !defined(_MSC_VER) typedef unsigned int word32; -#else - typedef unsigned long word32; -#endif #if defined(__GNUC__) || defined(__MWERKS__) # define WORD64_AVAILABLE @@ -184,14 +180,46 @@ NAMESPACE_END #endif #ifdef _MSC_VER + // 4231: nonstandard extension used : 'extern' before template explicit instantiation // 4250: dominance + // 4251: member needs to have dll-interface + // 4275: base needs to have dll-interface // 4660: explicitly instantiating a class that's already implicitly instantiated // 4661: no suitable definition provided for explicit template instantiation request // 4786: identifer was truncated in debug information // 4355: 'this' : used in base member initializer list -# pragma warning(disable: 4250 4660 4661 4786 4355) +# pragma warning(disable: 4231 4250 4251 4275 4660 4661 4786 4355) #endif +#ifdef _MSC_VER + +#ifdef CRYPTOPP_EXPORTS +#define CRYPTOPP_IS_DLL +#define CRYPTOPP_DLL __declspec(dllexport) +#elif defined(CRYPTOPP_IMPORTS) +#define CRYPTOPP_IS_DLL +#define CRYPTOPP_DLL __declspec(dllimport) +#else +#define CRYPTOPP_DLL +#endif + +#define CRYPTOPP_API __stdcall + +#else // _MSC_VER + +#define CRYPTOPP_DLL +#define CRYPTOPP_API + +#endif // _MSC_VER + +#ifdef CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES +#define CRYPTOPP_MANUAL_EXTERN +#else +#define CRYPTOPP_MANUAL_EXTERN extern +#endif + +#define CRYPTOPP_DLL_TEMPLATE_CLASS CRYPTOPP_MANUAL_EXTERN template class CRYPTOPP_DLL + // ***************** determine availability of OS features ******************** #ifndef NO_OS_DEPENDENCE diff --git a/cryptdll.dsp b/cryptdll.dsp new file mode 100644 index 00000000..d7d68f12 --- /dev/null +++ b/cryptdll.dsp @@ -0,0 +1,545 @@ +# Microsoft Developer Studio Project File - Name="cryptdll" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102 + +CFG=cryptdll - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "cryptdll.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "cryptdll.mak" CFG="cryptdll - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "cryptdll - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE "cryptdll - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "Perforce Project" +# PROP Scc_LocalPath "." +CPP=cl.exe +MTL=midl.exe +RSC=rc.exe + +!IF "$(CFG)" == "cryptdll - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "cryptdll___Win32_Release" +# PROP BASE Intermediate_Dir "cryptdll___Win32_Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "DLL_Release" +# PROP Intermediate_Dir "DLL_Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "CRYPTDLL_EXPORTS" /YX /FD /c +# ADD CPP /nologo /G5 /Gz /MT /W3 /GX /Zi /O1 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "CRYPTOPP_EXPORTS" /D CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2=1 /D "USE_PRECOMPILED_HEADERS" /Yu"pch.h" /FD /Zm200 /c +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 +# ADD LINK32 advapi32.lib /nologo /base:"0x69000000" /dll /debug /machine:I386 /out:"DLL_Release/cryptopp.dll" /opt:ref /export:CryptoPP_Malloc=malloc /export:CryptoPP_Free=free +# SUBTRACT LINK32 /pdb:none +# Begin Custom Build +OutDir=.\DLL_Release +TargetPath=.\DLL_Release\cryptopp.dll +InputPath=.\DLL_Release\cryptopp.dll +SOURCE="$(InputPath)" + +"$(OutDir)\cryptopp.mac.done" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + CTRelease\cryptest mac_dll $(TargetPath) + echo mac done > $(OutDir)\cryptopp.mac.done + +# End Custom Build + +!ELSEIF "$(CFG)" == "cryptdll - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "cryptdll___Win32_Debug" +# PROP BASE Intermediate_Dir "cryptdll___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "DLL_Debug" +# PROP Intermediate_Dir "DLL_Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "CRYPTDLL_EXPORTS" /YX /FD /GZ /c +# ADD CPP /nologo /G5 /Gz /MDd /W3 /Gm /GX /Zi /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "CRYPTOPP_EXPORTS" /D CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2=1 /D "USE_PRECOMPILED_HEADERS" /Yu"pch.h" /FD /GZ /Zm200 /c +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32 +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept +# ADD LINK32 advapi32.lib /nologo /base:"0x69000000" /dll /incremental:no /debug /machine:I386 /out:"DLL_Debug/cryptopp.dll" /opt:ref +# SUBTRACT LINK32 /pdb:none +# Begin Custom Build +OutDir=.\DLL_Debug +TargetPath=.\DLL_Debug\cryptopp.dll +InputPath=.\DLL_Debug\cryptopp.dll +SOURCE="$(InputPath)" + +"$(OutDir)\cryptopp.mac.done" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" + CTDebug\cryptest mac_dll $(TargetPath) + echo mac done > $(OutDir)\cryptopp.mac.done + +# End Custom Build + +!ENDIF + +# Begin Target + +# Name "cryptdll - Win32 Release" +# Name "cryptdll - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\algebra.cpp +# End Source File +# Begin Source File + +SOURCE=.\algparam.cpp +# End Source File +# Begin Source File + +SOURCE=.\asn.cpp +# End Source File +# Begin Source File + +SOURCE=.\basecode.cpp +# End Source File +# Begin Source File + +SOURCE=.\cbcmac.cpp +# End Source File +# Begin Source File + +SOURCE=.\channels.cpp +# End Source File +# Begin Source File + +SOURCE=.\cryptlib.cpp +# End Source File +# Begin Source File + +SOURCE=.\des.cpp +# End Source File +# Begin Source File + +SOURCE=.\dessp.cpp +# End Source File +# Begin Source File + +SOURCE=.\dh.cpp +# End Source File +# Begin Source File + +SOURCE=.\dll.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + +SOURCE=.\dsa.cpp +# End Source File +# Begin Source File + +SOURCE=.\ec2n.cpp +# End Source File +# Begin Source File + +SOURCE=.\eccrypto.cpp +# End Source File +# Begin Source File + +SOURCE=.\ecp.cpp +# End Source File +# Begin Source File + +SOURCE=.\eprecomp.cpp +# End Source File +# Begin Source File + +SOURCE=.\files.cpp +# End Source File +# Begin Source File + +SOURCE=.\filters.cpp +# End Source File +# Begin Source File + +SOURCE=.\fips140.cpp +# End Source File +# Begin Source File + +SOURCE=.\fipstest.cpp +# End Source File +# Begin Source File + +SOURCE=.\gf2n.cpp +# End Source File +# Begin Source File + +SOURCE=.\gfpcrypt.cpp +# End Source File +# Begin Source File + +SOURCE=.\hex.cpp +# End Source File +# Begin Source File + +SOURCE=.\hmac.cpp +# End Source File +# Begin Source File + +SOURCE=.\integer.cpp +# End Source File +# Begin Source File + +SOURCE=.\iterhash.cpp +# End Source File +# Begin Source File + +SOURCE=.\misc.cpp +# End Source File +# Begin Source File + +SOURCE=.\modes.cpp +# End Source File +# Begin Source File + +SOURCE=.\modexppc.cpp +# End Source File +# Begin Source File + +SOURCE=.\mqueue.cpp +# End Source File +# Begin Source File + +SOURCE=.\nbtheory.cpp +# End Source File +# Begin Source File + +SOURCE=.\oaep.cpp +# End Source File +# Begin Source File + +SOURCE=.\osrng.cpp +# End Source File +# Begin Source File + +SOURCE=.\pch.cpp +# ADD CPP /Yc"pch.h" +# End Source File +# Begin Source File + +SOURCE=.\pkcspad.cpp +# End Source File +# Begin Source File + +SOURCE=.\pubkey.cpp +# End Source File +# Begin Source File + +SOURCE=.\queue.cpp +# End Source File +# Begin Source File + +SOURCE=.\randpool.cpp +# End Source File +# Begin Source File + +SOURCE=.\rdtables.cpp +# End Source File +# Begin Source File + +SOURCE=.\rijndael.cpp +# End Source File +# Begin Source File + +SOURCE=.\rng.cpp +# End Source File +# Begin Source File + +SOURCE=.\rsa.cpp +# End Source File +# Begin Source File + +SOURCE=.\sha.cpp +# End Source File +# Begin Source File + +SOURCE=.\simple.cpp +# End Source File +# Begin Source File + +SOURCE=.\skipjack.cpp +# End Source File +# Begin Source File + +SOURCE=.\strciphr.cpp +# End Source File +# Begin Source File + +SOURCE=.\trdlocal.cpp +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter ".h" +# Begin Source File + +SOURCE=.\aes.h +# End Source File +# Begin Source File + +SOURCE=.\algebra.h +# End Source File +# Begin Source File + +SOURCE=.\algparam.h +# End Source File +# Begin Source File + +SOURCE=.\argnames.h +# End Source File +# Begin Source File + +SOURCE=.\asn.h +# End Source File +# Begin Source File + +SOURCE=.\basecode.h +# End Source File +# Begin Source File + +SOURCE=.\cbcmac.h +# End Source File +# Begin Source File + +SOURCE=.\channels.h +# End Source File +# Begin Source File + +SOURCE=.\config.h +# End Source File +# Begin Source File + +SOURCE=.\cryptlib.h +# End Source File +# Begin Source File + +SOURCE=.\des.h +# End Source File +# Begin Source File + +SOURCE=.\dh.h +# End Source File +# Begin Source File + +SOURCE=.\dll.h +# End Source File +# Begin Source File + +SOURCE=.\dsa.h +# End Source File +# Begin Source File + +SOURCE=.\ec2n.h +# End Source File +# Begin Source File + +SOURCE=.\eccrypto.h +# End Source File +# Begin Source File + +SOURCE=.\ecp.h +# End Source File +# Begin Source File + +SOURCE=.\eprecomp.h +# End Source File +# Begin Source File + +SOURCE=.\files.h +# End Source File +# Begin Source File + +SOURCE=.\filters.h +# End Source File +# Begin Source File + +SOURCE=.\fips140.h +# End Source File +# Begin Source File + +SOURCE=.\fltrimpl.h +# End Source File +# Begin Source File + +SOURCE=.\gf2n.h +# End Source File +# Begin Source File + +SOURCE=.\gfpcrypt.h +# End Source File +# Begin Source File + +SOURCE=.\hex.h +# End Source File +# Begin Source File + +SOURCE=.\hmac.h +# End Source File +# Begin Source File + +SOURCE=.\integer.h +# End Source File +# Begin Source File + +SOURCE=.\iterhash.h +# End Source File +# Begin Source File + +SOURCE=.\mdc.h +# End Source File +# Begin Source File + +SOURCE=.\misc.h +# End Source File +# Begin Source File + +SOURCE=.\modarith.h +# End Source File +# Begin Source File + +SOURCE=.\modes.h +# End Source File +# Begin Source File + +SOURCE=.\modexppc.h +# End Source File +# Begin Source File + +SOURCE=.\mqueue.h +# End Source File +# Begin Source File + +SOURCE=.\mqv.h +# End Source File +# Begin Source File + +SOURCE=.\nbtheory.h +# End Source File +# Begin Source File + +SOURCE=.\oaep.h +# End Source File +# Begin Source File + +SOURCE=.\oids.h +# End Source File +# Begin Source File + +SOURCE=.\osrng.h +# End Source File +# Begin Source File + +SOURCE=.\pch.h +# End Source File +# Begin Source File + +SOURCE=.\pkcspad.h +# End Source File +# Begin Source File + +SOURCE=.\pubkey.h +# End Source File +# Begin Source File + +SOURCE=.\queue.h +# End Source File +# Begin Source File + +SOURCE=.\randpool.h +# End Source File +# Begin Source File + +SOURCE=.\rijndael.h +# End Source File +# Begin Source File + +SOURCE=.\rng.h +# End Source File +# Begin Source File + +SOURCE=.\rsa.h +# End Source File +# Begin Source File + +SOURCE=.\secblock.h +# End Source File +# Begin Source File + +SOURCE=.\seckey.h +# End Source File +# Begin Source File + +SOURCE=.\sha.h +# End Source File +# Begin Source File + +SOURCE=.\simple.h +# End Source File +# Begin Source File + +SOURCE=.\skipjack.h +# End Source File +# Begin Source File + +SOURCE=.\smartptr.h +# End Source File +# Begin Source File + +SOURCE=.\stdcpp.h +# End Source File +# Begin Source File + +SOURCE=.\strciphr.h +# End Source File +# Begin Source File + +SOURCE=.\trdlocal.h +# End Source File +# Begin Source File + +SOURCE=.\words.h +# End Source File +# End Group +# Begin Source File + +SOURCE=.\cryptopp.rc +# End Source File +# End Target +# End Project diff --git a/cryptest.dsp b/cryptest.dsp index 33bbe2a5..a6f3ae1e 100644 --- a/cryptest.dsp +++ b/cryptest.dsp @@ -25,8 +25,8 @@ CFG=cryptest - Win32 Debug # Begin Project # PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" +# PROP Scc_ProjName "Perforce Project" +# PROP Scc_LocalPath "." CPP=cl.exe RSC=rc.exe @@ -45,7 +45,7 @@ RSC=rc.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /G5 /Gz /MT /W3 /GX /Zi /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm200 /c -# ADD CPP /nologo /G5 /Gz /MT /W3 /GX /Zi /O2 /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "WIN32" /YX /FD /Zm200 /c +# ADD CPP /nologo /G5 /Gz /MD /W3 /GX /Zi /O2 /D "NDEBUG" /D "CRYPTOPP_IMPORTS" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm400 /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe @@ -53,11 +53,11 @@ BSC32=bscmake.exe # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /OPT:NOWIN98 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /OPT:NOWIN98 /OPT:REF /OPT:ICF -# SUBTRACT LINK32 /pdb:none +# ADD LINK32 Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /out:"DLL_Release/cryptest.exe" /libpath:"DLL_Release" /OPT:NOWIN98 /OPT:REF /OPT:ICF +# SUBTRACT LINK32 /pdb:none /incremental:yes # Begin Special Build Tool SOURCE="$(InputPath)" -PostBuild_Cmds=echo This configuration is used to build a static binary for FIPS 140 evaluation by a testing laboratory. echo Crypto++ users should not build this configuration directly. +PreLink_Cmds=echo This configuration requires cryptopp.dll. echo You can build it yourself using the cryptdll project, or echo obtain a pre-built, FIPS 140-2 validated DLL. If you build it yourself echo the resulting DLL will not be considered FIPS validated echo unless it undergoes FIPS validation. # End Special Build Tool !ELSEIF "$(CFG)" == "cryptest - Win32 FIPS 140 Debug" @@ -75,7 +75,7 @@ PostBuild_Cmds=echo This configuration is used to build a static binary for FIPS # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm200 /c -# ADD CPP /nologo /G5 /Gz /MTd /W3 /GX /ZI /Od /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "WIN32" /YX /FD /Zm300 /c +# ADD CPP /nologo /G5 /Gz /MDd /W3 /GX /ZI /Od /D "_DEBUG" /D "CRYPTOPP_IMPORTS" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm400 /c # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe @@ -83,10 +83,10 @@ BSC32=bscmake.exe # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /OPT:NOWIN98 -# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept /OPT:NOWIN98 +# ADD LINK32 Ws2_32.lib /nologo /subsystem:console /debug /machine:I386 /out:"DLL_Debug/cryptest.exe" /pdbtype:sept /libpath:"DLL_Debug" /OPT:NOWIN98 # Begin Special Build Tool SOURCE="$(InputPath)" -PostBuild_Cmds=echo This configuration is used to build a static binary for FIPS 140 evaluation by a testing laboratory. echo Crypto++ users should not build this configuration directly. +PreLink_Cmds=echo This configuration requires cryptopp.dll. echo You can build it yourself using the cryptdll project, or echo obtain a pre-built, FIPS 140-2 validated DLL. If you build it yourself echo the resulting DLL will not be considered FIPS validated echo unless it undergoes FIPS validation. # End Special Build Tool !ELSEIF "$(CFG)" == "cryptest - Win32 Release" @@ -103,7 +103,7 @@ PostBuild_Cmds=echo This configuration is used to build a static binary for FIPS # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /MT /W3 /GX /Zi /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm200 /c +# ADD CPP /nologo /MT /W3 /GX /Zi /O2 /D "NDEBUG" /D "CRYPTOPP_NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm400 /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" BSC32=bscmake.exe @@ -128,7 +128,7 @@ LINK32=link.exe # PROP Ignore_Export_Lib 0 # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /MTd /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm300 /c +# ADD CPP /nologo /MTd /W3 /GX /ZI /Od /D "_DEBUG" /D "CRYPTOPP_NO_DLL" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /YX /FD /Zm400 /c # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" BSC32=bscmake.exe @@ -392,6 +392,10 @@ SOURCE=.\datatest.cpp # End Source File # Begin Source File +SOURCE=.\dlltest.cpp +# End Source File +# Begin Source File + SOURCE=.\factory.h # End Source File # Begin Source File diff --git a/cryptest.dsw b/cryptest.dsw index bce8473e..2260dbf9 100644 --- a/cryptest.dsw +++ b/cryptest.dsw @@ -3,10 +3,33 @@ Microsoft Developer Studio Workspace File, Format Version 6.00 ############################################################################### +Project: "cryptdll"=.\cryptdll.dsp - Package Owner=<4> + +Package=<5> +{{{ + begin source code control + Perforce Project + . + end source code control +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name cryptest + End Project Dependency +}}} + +############################################################################### + Project: "cryptest"=.\cryptest.dsp - Package Owner=<4> Package=<5> {{{ + begin source code control + Perforce Project + . + end source code control }}} Package=<4> @@ -22,6 +45,10 @@ Project: "cryptlib"=.\cryptlib.dsp - Package Owner=<4> Package=<5> {{{ + begin source code control + Perforce Project + . + end source code control }}} Package=<4> @@ -30,6 +57,25 @@ Package=<4> ############################################################################### +Project: "dlltest"=.\dlltest.dsp - Package Owner=<4> + +Package=<5> +{{{ + begin source code control + Perforce Project + . + end source code control +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name cryptdll + End Project Dependency +}}} + +############################################################################### + Global: Package=<5> diff --git a/cryptlib.cpp b/cryptlib.cpp index 5254c85d..1412ab9b 100644 --- a/cryptlib.cpp +++ b/cryptlib.cpp @@ -1,6 +1,9 @@ // cryptlib.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "cryptlib.h" #include "misc.h" #include "filters.h" @@ -37,7 +40,7 @@ Algorithm::Algorithm(bool checkSelfTestStatus) throw SelfTestFailure("Cryptographic algorithms are disabled before the power-up self tests are performed."); if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_FAILED) - throw SelfTestFailure("Cryptographic algorithms are disabled after power-up a self test failed."); + throw SelfTestFailure("Cryptographic algorithms are disabled after a power-up self test failed."); } } @@ -691,3 +694,5 @@ void AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair(RandomNumberGener } NAMESPACE_END + +#endif diff --git a/cryptlib.dsp b/cryptlib.dsp index 1c32dd01..e91ea269 100644 --- a/cryptlib.dsp +++ b/cryptlib.dsp @@ -25,8 +25,8 @@ CFG=cryptlib - Win32 Debug # Begin Project # PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" +# PROP Scc_ProjName "Perforce Project" +# PROP Scc_LocalPath "." CPP=cl.exe RSC=rc.exe @@ -43,7 +43,7 @@ RSC=rc.exe # PROP Intermediate_Dir "FIPS_140_Release" # PROP Target_Dir "" # ADD BASE CPP /nologo /G5 /Gz /MT /W3 /GX /Zi /O2 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /Yu"pch.h" /FD /c -# ADD CPP /nologo /G5 /Gz /MT /W3 /GX /Zi /O2 /D "NDEBUG" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /D "WIN32" /D CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2=1 /Yu"pch.h" /Fd"FIPS_140_Release/cryptopp" /FD /c +# ADD CPP /nologo /G5 /Gz /MD /W3 /GX /Zi /O2 /D "NDEBUG" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /D "WIN32" /D "CRYPTOPP_IMPORTS" /Yu"pch.h" /Fd"FIPS_140_Release/cryptopp" /FD /c # ADD BASE RSC /l 0x409 # ADD RSC /l 0x409 BSC32=bscmake.exe @@ -51,7 +51,7 @@ BSC32=bscmake.exe # ADD BSC32 /nologo LIB32=link.exe -lib # ADD BASE LIB32 /nologo -# ADD LIB32 /nologo /out:"FIPS_140_Release\cryptopp.lib" +# ADD LIB32 /nologo !ELSEIF "$(CFG)" == "cryptlib - Win32 FIPS 140 Debug" @@ -66,7 +66,7 @@ LIB32=link.exe -lib # PROP Intermediate_Dir "FIPS_140_Debug" # PROP Target_Dir "" # ADD BASE CPP /nologo /MTd /W3 /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /Yu"pch.h" /FD /c -# ADD CPP /nologo /G5 /Gz /MTd /W3 /GX /ZI /Od /D "_DEBUG" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /D "WIN32" /D CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2=1 /Yu"pch.h" /Fd"FIPS_140_Debug/cryptopp" /FD /c +# ADD CPP /nologo /G5 /Gz /MDd /W3 /GX /ZI /Od /D "_DEBUG" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /D "WIN32" /D "CRYPTOPP_IMPORTS" /Yu"pch.h" /Fd"FIPS_140_Debug/cryptopp" /FD /c # ADD BASE RSC /l 0x409 # ADD RSC /l 0x409 BSC32=bscmake.exe @@ -74,7 +74,7 @@ BSC32=bscmake.exe # ADD BSC32 /nologo LIB32=link.exe -lib # ADD BASE LIB32 /nologo -# ADD LIB32 /nologo /out:"FIPS_140_Debug\cryptopp.lib" +# ADD LIB32 /nologo !ELSEIF "$(CFG)" == "cryptlib - Win32 Release" @@ -89,7 +89,7 @@ LIB32=link.exe -lib # PROP Intermediate_Dir "Release" # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MT /W3 /GX /Zi /O2 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /Yu"pch.h" /FD /c +# ADD CPP /nologo /MT /W3 /GX /Zi /O2 /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /D "CRYPTOPP_NO_DLL" /Yu"pch.h" /FD /c # ADD BASE RSC /l 0x409 # ADD RSC /l 0x409 BSC32=bscmake.exe @@ -112,7 +112,7 @@ LIB32=link.exe -lib # PROP Intermediate_Dir "Debug" # PROP Target_Dir "" # ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c -# ADD CPP /nologo /MTd /W3 /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /Yu"pch.h" /FD /c +# ADD CPP /nologo /MTd /W3 /GX /ZI /Od /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "USE_PRECOMPILED_HEADERS" /D "CRYPTOPP_NO_DLL" /Yu"pch.h" /FD /c # ADD BASE RSC /l 0x409 # ADD RSC /l 0x409 BSC32=bscmake.exe @@ -242,6 +242,10 @@ SOURCE=.\casts.cpp # End Source File # Begin Source File +SOURCE=.\cbcmac.cpp +# End Source File +# Begin Source File + SOURCE=.\channels.cpp # End Source File # Begin Source File @@ -282,6 +286,11 @@ SOURCE=.\diamondt.cpp # End Source File # Begin Source File +SOURCE=.\dll.cpp +# SUBTRACT CPP /YX /Yc /Yu +# End Source File +# Begin Source File + SOURCE=.\dsa.cpp # End Source File # Begin Source File @@ -358,6 +367,10 @@ SOURCE=.\hex.cpp # End Source File # Begin Source File +SOURCE=.\hmac.cpp +# End Source File +# Begin Source File + SOURCE=.\hrtimer.cpp # End Source File # Begin Source File diff --git a/cryptlib.h b/cryptlib.h index 08201b3f..a1a2f1c4 100644 --- a/cryptlib.h +++ b/cryptlib.h @@ -4,7 +4,7 @@ classes that provide a uniform interface to this library. */ -/*! \mainpage Crypto++TM Library 5.1 Reference Manual +/*! \mainpage Crypto++TM Library 5.2 Reference Manual
Abstract Base Classes
cryptlib.h @@ -46,6 +46,26 @@ fips140.h
+In the FIPS 140-2 validated DLL version of Crypto++, only the following implementation class are available. +
+
Block Ciphers
+ AES, DES, DES_EDE2, DES_EDE3, SKIPJACK +
Cipher Modes (replace template parameter BC with one of the block ciphers above)
+ ECB_Mode , CTR_Mode , CBC_Mode , CFB_Mode , OFB_Mode +
Hash Functions
+ SHA, SHA256, SHA384, SHA512 +
Public Key Signature Schemes
+ RSASSA , DSA, ECDSA , ECDSA +
Message Authentication Codes
+ HMAC , HMAC , HMAC , HMAC , CBC_MAC , CBC_MAC , CBC_MAC +
Random Number Generators
+ AutoSeededX917RNG +
Key Agreement
+ #DH +
Public Key Cryptosystems
+ RSAES > +
+

This reference manual is a work in progress. Some classes are still lacking detailed descriptions.

Click here to download a zip archive containing this manual.

Thanks to Ryan Phillips for providing the Doxygen configuration file @@ -56,11 +76,7 @@ and getting me started with this manual. #define CRYPTOPP_CRYPTLIB_H #include "config.h" -#include -#include -#include -#include -#include +#include "stdcpp.h" NAMESPACE_BEGIN(CryptoPP) @@ -85,7 +101,7 @@ typedef EnumToType LittleEndian; typedef EnumToType BigEndian; //! base class for all exceptions thrown by Crypto++ -class Exception : public std::exception +class CRYPTOPP_DLL Exception : public std::exception { public: //! error types @@ -120,42 +136,42 @@ private: }; //! exception thrown when an invalid argument is detected -class InvalidArgument : public Exception +class CRYPTOPP_DLL InvalidArgument : public Exception { public: explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {} }; //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext -class InvalidDataFormat : public Exception +class CRYPTOPP_DLL InvalidDataFormat : public Exception { public: explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {} }; //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext -class InvalidCiphertext : public InvalidDataFormat +class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat { public: explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {} }; //! exception thrown by a class if a non-implemented method is called -class NotImplemented : public Exception +class CRYPTOPP_DLL NotImplemented : public Exception { public: explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {} }; //! exception thrown by a class when Flush(true) is called but it can't completely flush its buffers -class CannotFlush : public Exception +class CRYPTOPP_DLL CannotFlush : public Exception { public: explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {} }; //! error reported by the operating system -class OS_Error : public Exception +class CRYPTOPP_DLL OS_Error : public Exception { public: OS_Error(ErrorType errorType, const std::string s, const std::string& operation, int errorCode) @@ -173,7 +189,7 @@ protected: }; //! used to return decoding results -struct DecodingResult +struct CRYPTOPP_DLL DecodingResult { explicit DecodingResult() : isValidCoding(false), messageLength(0) {} explicit DecodingResult(unsigned int len) : isValidCoding(true), messageLength(len) {} @@ -249,21 +265,21 @@ public: } //! get a list of value names that can be retrieved - std::string GetValueNames() const + CRYPTOPP_DLL std::string GetValueNames() const {std::string result; GetValue("ValueNames", result); return result;} //! get a named value with type int /*! used to ensure we don't accidentally try to get an unsigned int or some other type when we mean int (which is the most common case) */ - bool GetIntValue(const char *name, int &value) const + CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const {return GetValue(name, value);} //! get a named value with type int, with default - int GetIntValueWithDefault(const char *name, int defaultValue) const + CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const {return GetValueWithDefault(name, defaultValue);} //! used by derived classes to check for type mismatch - static void ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving) + CRYPTOPP_DLL static void ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving) {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);} template @@ -273,14 +289,14 @@ public: throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); } - void GetRequiredIntParameter(const char *className, const char *name, int &value) const + CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const { if (!GetIntValue(name, value)) throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); } //! to be implemented by derived classes, users should use one of the above functions instead - virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0; + CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0; }; //! namespace containing value name definitions @@ -294,19 +310,19 @@ DOCUMENTED_NAMESPACE_BEGIN(Name) DOCUMENTED_NAMESPACE_END //! . -class NullNameValuePairs : public NameValuePairs +class CRYPTOPP_DLL NullNameValuePairs : public NameValuePairs { public: bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const {return false;} }; //! . -extern const NullNameValuePairs g_nullNameValuePairs; +extern CRYPTOPP_DLL const NullNameValuePairs g_nullNameValuePairs; // ******************************************************** //! interface for cloning objects, this is not implemented by most classes yet -class CRYPTOPP_NO_VTABLE Clonable +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable { public: virtual ~Clonable() {} @@ -316,7 +332,7 @@ public: //! interface for all crypto algorithms -class CRYPTOPP_NO_VTABLE Algorithm : public Clonable +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable { public: /*! When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true, @@ -328,7 +344,7 @@ public: //! keying interface for crypto algorithms that take byte strings as keys -class CRYPTOPP_NO_VTABLE SimpleKeyingInterface +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface { public: //! returns smallest valid key length in bytes */ @@ -399,7 +415,7 @@ protected: These classes should not be used directly, but only in combination with a mode class (see CipherModeDocumentation in modes.h). */ -class CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm { public: //! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock @@ -435,7 +451,7 @@ public: //! interface for the data processing part of stream ciphers -class CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm { public: //! return a reference to this object, @@ -498,7 +514,7 @@ public: be hashed in pieces by calling Update() on each piece followed by calling Final(). */ -class CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm { public: //! process more input @@ -519,6 +535,9 @@ public: //! size of the hash returned by Final() virtual unsigned int DigestSize() const =0; + //! block size of underlying compression function, or 0 if not block based + virtual unsigned int BlockSize() const {return 0;} + //! input to Update() should have length a multiple of this for optimal speed virtual unsigned int OptimalBlockSize() const {return 1;} @@ -559,7 +578,7 @@ protected: //! . template -class CRYPTOPP_NO_VTABLE SimpleKeyedTransformation : public T, public SimpleKeyingInterface +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyedTransformation : public T, public SimpleKeyingInterface { public: void ThrowIfInvalidKeyLength(unsigned int length) @@ -579,6 +598,10 @@ class MessageAuthenticationCode : public HashTransformation, public SimpleKeying typedef SimpleKeyedTransformation BlockCipher; typedef SimpleKeyedTransformation SymmetricCipher; typedef SimpleKeyedTransformation MessageAuthenticationCode; + +CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation; +CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation; +CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation; #endif #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY @@ -588,7 +611,7 @@ typedef SymmetricCipher StreamCipher; //! interface for random number generators /*! All return values are uniformly distributed over the range specified. */ -class CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm { public: //! generate new random byte and return it @@ -626,7 +649,7 @@ public: }; //! returns a reference that can be passed to functions that ask for a RNG but doesn't actually use it -RandomNumberGenerator & NullRNG(); +CRYPTOPP_DLL RandomNumberGenerator & NullRNG(); class WaitObjectContainer; @@ -670,7 +693,7 @@ public: \nosubgrouping */ -class CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable { public: // placed up here for CW8 @@ -929,11 +952,11 @@ BufferedTransformation & TheBitBucket(); //! interface for crypto material, such as public and private keys, and crypto parameters -class CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs { public: //! exception thrown when invalid crypto material is detected - class InvalidMaterial : public InvalidDataFormat + class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat { public: explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {} @@ -990,7 +1013,7 @@ public: //! interface for generatable crypto material, such as private keys and crypto parameters -class CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial { public: //! generate a random key or crypto parameters @@ -1005,25 +1028,25 @@ public: //! interface for public keys -class CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial { }; //! interface for private keys -class CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial { }; //! interface for crypto prameters -class CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial { }; //! interface for asymmetric algorithms -class CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm { public: //! returns a reference to the crypto material used by this object @@ -1041,7 +1064,7 @@ public: //! interface for asymmetric algorithms using public keys -class CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm { public: // VC60 workaround: no co-variant return type @@ -1054,7 +1077,7 @@ public: //! interface for asymmetric algorithms using private keys -class CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm { public: CryptoMaterial & AccessMaterial() {return AccessPrivateKey();} @@ -1066,7 +1089,7 @@ public: //! interface for key agreement algorithms -class CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm { public: CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();} @@ -1081,7 +1104,7 @@ public: /*! This class provides an interface common to encryptors and decryptors for querying their plaintext and ciphertext lengths. */ -class CRYPTOPP_NO_VTABLE PK_CryptoSystem +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem { public: virtual ~PK_CryptoSystem() {} @@ -1102,11 +1125,11 @@ public: //! interface for public-key encryptors -class CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : virtual public PK_CryptoSystem, public PublicKeyAlgorithm { public: //! . - class InvalidPlaintextLength : public Exception + class CRYPTOPP_DLL InvalidPlaintextLength : public Exception { public: InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {} @@ -1126,7 +1149,7 @@ public: //! interface for public-key decryptors -class CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : virtual public PK_CryptoSystem, public PrivateKeyAlgorithm { public: //! decrypt a byte string, and return the length of plaintext @@ -1147,7 +1170,7 @@ public: as RSA) whose ciphertext length and maximum plaintext length depend only on the key. */ -class CRYPTOPP_NO_VTABLE PK_FixedLengthCryptoSystem +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_FixedLengthCryptoSystem { public: //! @@ -1174,13 +1197,13 @@ class CRYPTOPP_NO_VTABLE PK_FixedLengthCryptoSystemImpl : public BASE, public PK //! interface for encryptors with fixed length ciphertext -class CRYPTOPP_NO_VTABLE PK_FixedLengthEncryptor : public PK_FixedLengthCryptoSystemImpl +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_FixedLengthEncryptor : public PK_FixedLengthCryptoSystemImpl { }; //! interface for decryptors with fixed length ciphertext -class CRYPTOPP_NO_VTABLE PK_FixedLengthDecryptor : public PK_FixedLengthCryptoSystemImpl +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_FixedLengthDecryptor : public PK_FixedLengthCryptoSystemImpl { public: //! decrypt a byte string, and return the length of plaintext @@ -1198,18 +1221,18 @@ public: /*! This class provides an interface common to signers and verifiers for querying scheme properties. */ -class CRYPTOPP_NO_VTABLE PK_SignatureScheme +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme { public: //! invalid key exception, may be thrown by any function in this class if the private or public key has a length that can't be used - class InvalidKeyLength : public Exception + class CRYPTOPP_DLL InvalidKeyLength : public Exception { public: InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {} }; //! key too short exception, may be thrown by any function in this class if the private or public key is too short to sign or verify anything - class KeyTooShort : public InvalidKeyLength + class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength { public: KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {} @@ -1247,7 +1270,7 @@ public: /*! Only Update() should be called on this class. No other functions inherited from HashTransformation should be called. */ -class CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation { public: //! should not be called on PK_MessageAccumulator @@ -1260,7 +1283,7 @@ public: //! interface for public-key signers -class CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm { public: //! create a new HashTransformation to accumulate the message to be signed @@ -1301,7 +1324,7 @@ public: recovery and the signature contains a non-empty recoverable message part. The Recovery* functions should be used in that case. */ -class CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm { public: //! create a new HashTransformation to accumulate the message to be verified @@ -1344,7 +1367,7 @@ public: by two parties in a key agreement protocol, along with the algorithms for generating key pairs and deriving agreed values. */ -class CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm { public: //! return length of agreed value produced @@ -1382,7 +1405,7 @@ public: key pairs. The long-lived key pair is called the static key pair, and the short-lived key pair is called the ephemeral key pair. */ -class CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm { public: //! return length of agreed value produced @@ -1539,7 +1562,7 @@ public: #endif //! BER Decode Exception Class, may be thrown during an ASN1 BER decode operation -class BERDecodeErr : public InvalidArgument +class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument { public: BERDecodeErr() : InvalidArgument("BER decode error") {} @@ -1547,7 +1570,7 @@ public: }; //! interface for encoding and decoding ASN1 objects -class CRYPTOPP_NO_VTABLE ASN1Object +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object { public: virtual ~ASN1Object() {} diff --git a/cryptopp.rc b/cryptopp.rc new file mode 100644 index 00000000..7f9913b2 --- /dev/null +++ b/cryptopp.rc @@ -0,0 +1,109 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 5,0,3,0 + PRODUCTVERSION 5,0,3,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "\0" + VALUE "CompanyName", "Wei Dai\0" + VALUE "FileDescription", "Crypto++® Library DLL\0" + VALUE "FileVersion", "5, 0, 3, 0\0" + VALUE "InternalName", "cryptopp\0" + VALUE "LegalCopyright", "Copyright © 1995-2003\0" + VALUE "LegalTrademarks", "Crypto++®\0" + VALUE "OriginalFilename", "cryptopp.dll\0" + VALUE "PrivateBuild", "\0" + VALUE "ProductName", "Crypto++® Library\0" + VALUE "ProductVersion", "5, 0, 3, 0\0" + VALUE "SpecialBuild", "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // !_MAC + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/des.cpp b/des.cpp index b3a58e50..c9f4a384 100644 --- a/des.cpp +++ b/des.cpp @@ -20,6 +20,8 @@ NAMESPACE_BEGIN(CryptoPP) +#ifndef CRYPTOPP_IMPORTS + static inline bool CheckParity(byte b) { unsigned int a = b ^ (b >> 4); @@ -445,6 +447,8 @@ void DES_EDE3::Base::ProcessAndXorBlock(const byte *inBlock, const byte *xorBloc Block::Put(xorBlock, outBlock)(r)(l); } +#endif // #ifndef CRYPTOPP_IMPORTS + void DES_XEX3::Base::UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length) { AssertValidKeyLength(length); diff --git a/des.h b/des.h index 5a7f2dfe..a6c56727 100644 --- a/des.h +++ b/des.h @@ -11,7 +11,7 @@ NAMESPACE_BEGIN(CryptoPP) struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8> { - static const char *StaticAlgorithmName() {return "DES";} + CRYPTOPP_DLL static const char * StaticAlgorithmName() {return "DES";} }; /// DES @@ -21,7 +21,7 @@ struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8> check or correct the parity bits if you wish. */ class DES : public DES_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length = 8); @@ -42,19 +42,19 @@ public: //! correct DES key parity bits static void CorrectKeyParityBits(byte *key); - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; struct DES_EDE2_Info : public FixedBlockSize<8>, public FixedKeyLength<16> { - static const char *StaticAlgorithmName() {return "DES-EDE2";} + CRYPTOPP_DLL static const char * StaticAlgorithmName() {return "DES-EDE2";} }; /// DES-EDE2 class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -65,19 +65,19 @@ class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; struct DES_EDE3_Info : public FixedBlockSize<8>, public FixedKeyLength<24> { - static const char *StaticAlgorithmName() {return "DES-EDE3";} + CRYPTOPP_DLL static const char * StaticAlgorithmName() {return "DES-EDE3";} }; /// DES-EDE3 class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length); @@ -88,8 +88,8 @@ class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24> @@ -100,7 +100,7 @@ struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24> /// DES-XEX3, AKA DESX class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length); @@ -112,8 +112,8 @@ class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef DES::Encryption DESEncryption; diff --git a/dessp.cpp b/dessp.cpp index 1f7a9510..4ef9d18b 100644 --- a/dessp.cpp +++ b/dessp.cpp @@ -1,6 +1,9 @@ // This file is mostly generated by Phil Karn's gensp.c #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "des.h" NAMESPACE_BEGIN(CryptoPP) @@ -88,3 +91,5 @@ const word32 DES::Base::Spbox[8][64] = { }; NAMESPACE_END + +#endif diff --git a/dh.cpp b/dh.cpp index fc818b72..22097a05 100644 --- a/dh.cpp +++ b/dh.cpp @@ -1,6 +1,9 @@ // dh.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "dh.h" NAMESPACE_BEGIN(CryptoPP) @@ -12,3 +15,5 @@ void DH_TestInstantiations() } NAMESPACE_END + +#endif diff --git a/dh.h b/dh.h index 2514333b..31fa7985 100644 --- a/dh.h +++ b/dh.h @@ -85,6 +85,8 @@ private: GroupParameters m_groupParameters; }; +CRYPTOPP_DLL_TEMPLATE_CLASS DH_Domain; + //! Diffie-Hellman in GF(p) with key validation typedef DH_Domain DH; diff --git a/diamond.h b/diamond.h index 4646b460..e5ac3e71 100644 --- a/diamond.h +++ b/diamond.h @@ -17,7 +17,7 @@ struct Diamond2_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 1 /// Diamond2 class Diamond2 : public Diamond2_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length, unsigned int rounds); @@ -50,8 +50,8 @@ class Diamond2 : public Diamond2_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Diamond2::Encryption Diamond2Encryption; @@ -65,7 +65,7 @@ struct Diamond2Lite_Info : public FixedBlockSize<8>, public VariableKeyLength<16 /// Diamond2Lite class Diamond2Lite : public Diamond2Lite_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length, unsigned int rounds); @@ -97,8 +97,8 @@ class Diamond2Lite : public Diamond2Lite_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Diamond2Lite::Encryption Diamond2LiteEncryption; diff --git a/dll.cpp b/dll.cpp new file mode 100644 index 00000000..29f4aa57 --- /dev/null +++ b/dll.cpp @@ -0,0 +1,100 @@ +// dll.cpp - written and placed in the public domain by Wei Dai + +#ifndef CRYPTOPP_IMPORTS + +#define CRYPTOPP_MANUALLY_INSTANTIATE_TEMPLATES + +#include "dll.h" +#pragma warning(default: 4660) + +#include +#include + +#include "strciphr.cpp" +#include "algebra.cpp" +#include "eprecomp.cpp" +#include "eccrypto.cpp" +#include "iterhash.cpp" +#include "oaep.cpp" + +static const byte s_moduleMac[CryptoPP::HMAC::DIGESTSIZE] = "reserved for mac"; +static HMODULE s_hModule = NULL; + +NAMESPACE_BEGIN(CryptoPP) + +template<> const byte PKCS_DigestDecoration::decoration[] = {0x30,0x21,0x30,0x09,0x06,0x05,0x2B,0x0E,0x03,0x02,0x1A,0x05,0x00,0x04,0x14}; +template<> const unsigned int PKCS_DigestDecoration::length = sizeof(PKCS_DigestDecoration::decoration); + +void DoDllPowerUpSelfTest() +{ + char moduleFileName[_MAX_PATH]; + GetModuleFileNameA(s_hModule, moduleFileName, sizeof(moduleFileName)); + CryptoPP::DoPowerUpSelfTest(moduleFileName, s_moduleMac); +} + +NAMESPACE_END + +#endif + +#ifdef CRYPTOPP_EXPORTS + +USING_NAMESPACE(CryptoPP) + +static PNew s_pNew = NULL; +static PDelete s_pDelete = NULL; + +void * _cdecl operator new (size_t size) +{ + if (!s_pNew) + { + HMODULE hExe = GetModuleHandle(NULL); + PGetNewAndDelete pGetNewAndDelete = (PGetNewAndDelete)GetProcAddress(hExe, "GetNewAndDeleteForCryptoPP"); + if (pGetNewAndDelete) + pGetNewAndDelete(s_pNew, s_pDelete); + else + { + PSetNewAndDelete pSetNewAndDelete = (PSetNewAndDelete)GetProcAddress(hExe, "SetNewAndDeleteFromCryptoPP"); + if (pSetNewAndDelete) + { + _set_new_mode(1); + s_pNew = &malloc; + s_pDelete = &free; + pSetNewAndDelete(s_pNew, s_pDelete, &_set_new_handler); + } + else + { + HMODULE hCrt = GetModuleHandle("msvcrtd"); + if (!hCrt) + hCrt = GetModuleHandle("msvcrt"); + if (hCrt) + { + s_pNew = (PNew)GetProcAddress(hCrt, "??2@YAPAXI@Z"); // operator new + s_pDelete = (PDelete)GetProcAddress(hCrt, "??3@YAXPAX@Z"); // operator delete + } + } + } + + if (!s_pNew || !s_pDelete) + OutputDebugString("Crypto++ was not able to obtain new and delete function pointers."); + } + return s_pNew(size); +} + +void _cdecl operator delete (void * p) +{ + s_pDelete(p); +} + +BOOL APIENTRY DllMain(HANDLE hModule, + DWORD ul_reason_for_call, + LPVOID lpReserved) +{ + if (ul_reason_for_call == DLL_PROCESS_ATTACH) + { + s_hModule = (HMODULE)hModule; + DoDllPowerUpSelfTest(); + } + return TRUE; +} + +#endif diff --git a/dll.h b/dll.h new file mode 100644 index 00000000..a8b07d69 --- /dev/null +++ b/dll.h @@ -0,0 +1,64 @@ +#ifndef CRYPTOPP_DLL_H +#define CRYPTOPP_DLL_H + +#if !defined(CRYPTOPP_EXPORTS) && !defined(CRYPTOPP_IMPORTS) && !defined(CRYPTOPP_NO_DLL) +#ifdef CRYPTOPP_CONFIG_H +#error To use the DLL version of Crypto++, this file must be included before any other Crypto++ header files. +#endif +#define CRYPTOPP_IMPORTS +#endif + +#include "aes.h" +#include "cbcmac.h" +#include "channels.h" +#include "des.h" +#include "dh.h" +#include "dsa.h" +#include "ec2n.h" +#include "eccrypto.h" +#include "ecp.h" +#include "files.h" +#include "fips140.h" +#include "hex.h" +#include "hmac.h" +#include "modes.h" +#include "mqueue.h" +#include "nbtheory.h" +#include "osrng.h" +#include "pkcspad.h" +#include "randpool.h" +#include "rsa.h" +#include "sha.h" +#include "skipjack.h" +#include "trdlocal.h" + +#ifdef CRYPTOPP_IMPORTS + +#ifdef _DLL +// cause CRT DLL to be initialized before Crypto++ so that we can use malloc and free during DllMain() +#ifdef NDEBUG +#pragma comment(lib, "msvcrt") +#else +#pragma comment(lib, "msvcrtd") +#endif +#endif + +#pragma comment(lib, "cryptopp") + +#endif // #ifdef CRYPTOPP_IMPORTS + +#include // for _PNH + +NAMESPACE_BEGIN(CryptoPP) + +typedef void * (_cdecl * PNew)(size_t); +typedef void (_cdecl * PDelete)(void *); +typedef void (_cdecl * PGetNewAndDelete)(PNew &, PDelete &); +typedef _PNH (_cdecl * PSetNewHandler)(_PNH); +typedef void (_cdecl * PSetNewAndDelete)(PNew, PDelete, PSetNewHandler); + +CRYPTOPP_DLL void DoDllPowerUpSelfTest(); + +NAMESPACE_END + +#endif diff --git a/dlltest.cpp b/dlltest.cpp new file mode 100644 index 00000000..eb11feb4 --- /dev/null +++ b/dlltest.cpp @@ -0,0 +1,178 @@ +#include "dll.h" +#include + +USING_NAMESPACE(CryptoPP) +USING_NAMESPACE(std) + +void FIPS140_SampleApplication() +{ + if (!FIPS_140_2_ComplianceEnabled()) + { + cerr << "FIPS-140-2 compliance was turned off at compile time.\n"; + abort(); + } + + // check self test status + if (GetPowerUpSelfTestStatus() != POWER_UP_SELF_TEST_PASSED) + { + cerr << "Automatic power-up self test failed.\n"; + abort(); + } + cout << "0. Automatic power-up self test passed.\n"; + + // simulate a power-up self test error + SimulatePowerUpSelfTestFailure(); + try + { + // trying to use a crypto algorithm after power-up self test error will result in an exception + DES::Encryption des; + + // should not be here + cerr << "Use of DES failed to cause an exception after power-up self test error.\n"; + abort(); + } + catch (SelfTestFailure &e) + { + cout << "1. Caught expected exception when simulating self test failure. Exception message follows: "; + cout << e.what() << endl; + } + + // clear the self test error state and redo power-up self test + DoDllPowerUpSelfTest(); + if (GetPowerUpSelfTestStatus() != POWER_UP_SELF_TEST_PASSED) + { + cerr << "Re-do power-up self test failed.\n"; + abort(); + } + cout << "2. Re-do power-up self test passed.\n"; + + // encrypt and decrypt + const byte key[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; + const byte iv[] = {0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef}; + const byte plaintext[] = { // "Now is the time for all " without tailing 0 + 0x4e,0x6f,0x77,0x20,0x69,0x73,0x20,0x74, + 0x68,0x65,0x20,0x74,0x69,0x6d,0x65,0x20, + 0x66,0x6f,0x72,0x20,0x61,0x6c,0x6c,0x20}; + byte ciphertext[24]; + byte decrypted[24]; + + CFB_Mode::Encryption encryption_DES_CBC; + encryption_DES_CBC.SetKeyWithIV(key, 8, iv); + encryption_DES_CBC.ProcessString(ciphertext, plaintext, 24); + + CFB_Mode::Decryption decryption_DES_CBC; + decryption_DES_CBC.SetKeyWithIV(key, 8, iv); + decryption_DES_CBC.ProcessString(decrypted, ciphertext, 24); + + if (memcmp(plaintext, decrypted, 24) != 0) + { + cerr << "DES-CBC Encryption/decryption failed.\n"; + abort(); + } + cout << "3. DES-CBC Encryption/decryption succeeded.\n"; + + // hash + const byte message[] = {'a', 'b', 'c'}; + const byte expectedDigest[] = {0xA9,0x99,0x3E,0x36,0x47,0x06,0x81,0x6A,0xBA,0x3E,0x25,0x71,0x78,0x50,0xC2,0x6C,0x9C,0xD0,0xD8,0x9D}; + byte digest[20]; + + SHA1 sha; + sha.Update(message, 3); + sha.Final(digest); + + if (memcmp(digest, expectedDigest, 20) != 0) + { + cerr << "SHA-1 hash failed.\n"; + abort(); + } + cout << "4. SHA-1 hash succeeded.\n"; + + // create auto-seeded X9.17 RNG object, if available +#ifdef OS_RNG_AVAILABLE + AutoSeededX917RNG rng; +#else + // this is used to allow this function to compile on platforms that don't have auto-seeded RNGs + RandomNumberGenerator &rng(NullRNG()); +#endif + + // generate DSA key + DSA::PrivateKey dsaPrivateKey; + dsaPrivateKey.GenerateRandomWithKeySize(rng, 1024); + DSA::PublicKey dsaPublicKey; + dsaPublicKey.AssignFrom(dsaPrivateKey); + if (!dsaPrivateKey.Validate(rng, 3) || !dsaPublicKey.Validate(rng, 3)) + { + cerr << "DSA key generation failed.\n"; + abort(); + } + cout << "5. DSA key generation succeeded.\n"; + + // encode DSA key + std::string encodedDsaPublicKey, encodedDsaPrivateKey; + dsaPublicKey.DEREncode(StringSink(encodedDsaPublicKey).Ref()); + dsaPrivateKey.DEREncode(StringSink(encodedDsaPrivateKey).Ref()); + + // decode DSA key + DSA::PrivateKey decodedDsaPrivateKey; + decodedDsaPrivateKey.BERDecode(StringStore(encodedDsaPrivateKey).Ref()); + DSA::PublicKey decodedDsaPublicKey; + decodedDsaPublicKey.BERDecode(StringStore(encodedDsaPublicKey).Ref()); + + if (!decodedDsaPrivateKey.Validate(rng, 3) || !decodedDsaPublicKey.Validate(rng, 3)) + { + cerr << "DSA key encode/decode failed.\n"; + abort(); + } + cout << "6. DSA key encode/decode succeeded.\n"; + + // sign and verify + byte signature[40]; + DSA::Signer signer(dsaPrivateKey); + assert(signer.SignatureLength() == 40); + signer.SignMessage(rng, message, 3, signature); + + DSA::Verifier verifier(dsaPublicKey); + if (!verifier.VerifyMessage(message, 3, signature, sizeof(signature))) + { + cerr << "DSA signature and verification failed.\n"; + abort(); + } + cout << "7. DSA signature and verification succeeded.\n"; + + + // try to verify an invalid signature + signature[0] ^= 1; + if (verifier.VerifyMessage(message, 3, signature, sizeof(signature))) + { + cerr << "DSA signature verification failed to detect bad signature.\n"; + abort(); + } + cout << "8. DSA signature verification successfully detected bad signature.\n"; + + // try to use an invalid key length + try + { + encryption_DES_CBC.SetKey(key, 5); + + // should not be here + cerr << "DES implementation did not detect use of invalid key length.\n"; + abort(); + } + catch (InvalidArgument &e) + { + cout << "9. Caught expected exception when using invalid key length. Exception message follows: "; + cout << e.what() << endl; + } + + cout << "\nFIPS 140-2 Sample Application completed normally.\n"; +} + +#ifdef CRYPTOPP_DLL_ONLY + +int __cdecl main() +{ + FIPS140_SampleApplication(); + return 0; +} + +#endif diff --git a/dlltest.dsp b/dlltest.dsp new file mode 100644 index 00000000..7a71a598 --- /dev/null +++ b/dlltest.dsp @@ -0,0 +1,90 @@ +# Microsoft Developer Studio Project File - Name="dlltest" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=dlltest - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "dlltest.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "dlltest.mak" CFG="dlltest - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "dlltest - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "dlltest - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "Perforce Project" +# PROP Scc_LocalPath "." +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "dlltest - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "dlltest___Win32_Release" +# PROP BASE Intermediate_Dir "dlltest___Win32_Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "dlltest___Win32_Release" +# PROP Intermediate_Dir "dlltest___Win32_Release" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /Gz /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "CRYPTOPP_DLL_ONLY" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /out:"DLL_Release/dlltest.exe" /libpath:"DLL_Release" + +!ELSEIF "$(CFG)" == "dlltest - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "dlltest___Win32_Debug" +# PROP BASE Intermediate_Dir "dlltest___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "dlltest___Win32_Debug" +# PROP Intermediate_Dir "dlltest___Win32_Debug" +# PROP Ignore_Export_Lib 0 +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /Gz /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "CRYPTOPP_DLL_ONLY" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 /nologo /subsystem:console /debug /machine:I386 /out:"DLL_Debug/dlltest.exe" /pdbtype:sept /libpath:"DLL_Debug" + +!ENDIF + +# Begin Target + +# Name "dlltest - Win32 Release" +# Name "dlltest - Win32 Debug" +# Begin Source File + +SOURCE=.\dlltest.cpp +# End Source File +# End Target +# End Project diff --git a/dmac.h b/dmac.h index e431c447..521ba448 100644 --- a/dmac.h +++ b/dmac.h @@ -35,7 +35,7 @@ private: and Charles Rackoff. T should be BlockTransformation class. */ template -class DMAC : public MessageAuthenticationCodeTemplate > +class DMAC : public MessageAuthenticationCodeFinal > { public: DMAC() {} diff --git a/dsa.cpp b/dsa.cpp index 4bdbae61..c7e3da18 100644 --- a/dsa.cpp +++ b/dsa.cpp @@ -1,6 +1,9 @@ // dsa.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "dsa.h" #include "nbtheory.h" @@ -112,3 +115,5 @@ bool DSA::GeneratePrimes(const byte *seedIn, unsigned int g, int &counter, } NAMESPACE_END + +#endif diff --git a/ec2n.cpp b/ec2n.cpp index c6494efd..d668c4f0 100644 --- a/ec2n.cpp +++ b/ec2n.cpp @@ -1,6 +1,9 @@ // ec2n.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "ec2n.h" #include "asn.h" @@ -281,7 +284,6 @@ EC2N::Point EcPrecomputation::CascadeExponentiate(const Integer &exponent, } */ -template class AbstractGroup; -template class DL_FixedBasePrecomputationImpl; - NAMESPACE_END + +#endif diff --git a/ec2n.h b/ec2n.h index c2177e76..3cb42460 100644 --- a/ec2n.h +++ b/ec2n.h @@ -9,7 +9,7 @@ NAMESPACE_BEGIN(CryptoPP) //! Elliptic Curve Point -struct EC2NPoint +struct CRYPTOPP_DLL EC2NPoint { EC2NPoint() : identity(true) {} EC2NPoint(const PolynomialMod2 &x, const PolynomialMod2 &y) @@ -24,8 +24,10 @@ struct EC2NPoint PolynomialMod2 x, y; }; +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup; + //! Elliptic Curve over GF(2^n) -class EC2N : public AbstractGroup +class CRYPTOPP_DLL EC2N : public AbstractGroup { public: typedef GF2NP Field; @@ -73,12 +75,18 @@ public: const FieldElement & GetA() const {return m_a;} const FieldElement & GetB() const {return m_b;} + bool operator==(const EC2N &rhs) const + {return GetField() == rhs.GetField() && m_a == rhs.m_a && m_b == rhs.m_b;} + private: clonable_ptr m_field; FieldElement m_a, m_b; mutable Point m_R; }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation; + template class EcPrecomputation; //! . diff --git a/eccrypto.cpp b/eccrypto.cpp index b0042e89..a9345349 100644 --- a/eccrypto.cpp +++ b/eccrypto.cpp @@ -1,14 +1,19 @@ +// eccrypto.cpp - written and placed in the public domain by Wei Dai + #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "eccrypto.h" -#include "ec2n.h" -#include "ecp.h" #include "nbtheory.h" #include "oids.h" #include "hex.h" #include "argnames.h" +#include "ec2n.h" NAMESPACE_BEGIN(CryptoPP) +#ifndef NDEBUG static void ECDSA_TestInstantiations() { ECDSA::Signer t1; @@ -20,6 +25,7 @@ static void ECDSA_TestInstantiations() ECDH::Domain t7; ECMQV::Domain t8; } +#endif // VC60 workaround: complains when these functions are put into an anonymous namespace static Integer ConvertToInteger(const PolynomialMod2 &x) @@ -627,13 +633,6 @@ void DL_PrivateKey_EC::DEREncodeKey(BufferedTransformation &bt) const privateKey.MessageEnd(); } -// ****************************************************************** - -template class DL_GroupParameters_EC; -template class DL_GroupParameters_EC; -template class DL_PublicKey_EC; -template class DL_PublicKey_EC; -template class DL_PrivateKey_EC; -template class DL_PrivateKey_EC; - NAMESPACE_END + +#endif diff --git a/eccrypto.h b/eccrypto.h index dafa1c70..cb295a6a 100644 --- a/eccrypto.h +++ b/eccrypto.h @@ -1,5 +1,5 @@ #ifndef CRYPTOPP_ECCRYPTO_H -#define CRYPTOPP_ECCRTPTO_H +#define CRYPTOPP_ECCRYPTO_H /*! \file */ @@ -12,11 +12,11 @@ #include "gfpcrypt.h" #include "dh.h" #include "mqv.h" +#include "ecp.h" +#include "ec2n.h" NAMESPACE_BEGIN(CryptoPP) -template class EcPrecomputation; - //! Elliptic Curve Parameters /*! This class corresponds to the ASN.1 sequence of the same name in ANSI X9.62 (also SEC 1). @@ -117,6 +117,9 @@ public: const EllipticCurve& GetCurve() const {return m_groupPrecomputation.GetCurve();} + bool operator==(const ThisClass &rhs) const + {return DL_GroupParametersImpl >::operator==(rhs);} + #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY const Point& GetBasePoint() const {return GetSubgroupGenerator();} const Integer& GetBasePointOrder() const {return GetSubgroupOrder();} @@ -133,6 +136,11 @@ protected: mutable Integer m_k; // cofactor }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl >; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl >; + //! . template class DL_PublicKey_EC : public DL_PublicKeyImpl > @@ -150,6 +158,11 @@ public: void DEREncodeKey(BufferedTransformation &bt) const; }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl >; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl >; + //! . template class DL_PrivateKey_EC : public DL_PrivateKeyImpl > @@ -171,6 +184,9 @@ public: void DEREncodeKey(BufferedTransformation &bt) const; }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC; + //! Elliptic Curve Diffie-Hellman, AKA ECDH template ::DefaultCofactorOption> struct ECDH @@ -196,6 +212,9 @@ struct DL_Keys_EC template struct ECDSA; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest, ECDSA >; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest, ECDSA >; + //! . template struct DL_Keys_ECDSA @@ -204,6 +223,9 @@ struct DL_Keys_ECDSA typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest, ECDSA > PrivateKey; }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA; + //! . template class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA diff --git a/ecp.cpp b/ecp.cpp index cfbad96a..f13ee287 100644 --- a/ecp.cpp +++ b/ecp.cpp @@ -1,12 +1,14 @@ // ecp.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "ecp.h" #include "asn.h" #include "nbtheory.h" #include "algebra.cpp" -#include "eprecomp.cpp" NAMESPACE_BEGIN(CryptoPP) @@ -463,15 +465,6 @@ ECP::Point ECP::CascadeScalarMultiply(const Point &P, const Integer &k1, const P return AbstractGroup::CascadeScalarMultiply(P, k1, Q, k2); } -// ******************************************************** - -void EcPrecomputation::SetCurve(const ECP &ec) -{ - m_ec.reset(new ECP(ec, true)); - m_ecOriginal = ec; -} - -template class AbstractGroup; -template class DL_FixedBasePrecomputationImpl; - NAMESPACE_END + +#endif diff --git a/ecp.h b/ecp.h index 28822ee9..bc7303d1 100644 --- a/ecp.h +++ b/ecp.h @@ -9,7 +9,7 @@ NAMESPACE_BEGIN(CryptoPP) //! Elliptical Curve Point -struct ECPPoint +struct CRYPTOPP_DLL ECPPoint { ECPPoint() : identity(true) {} ECPPoint(const Integer &x, const Integer &y) @@ -24,8 +24,10 @@ struct ECPPoint Integer x, y; }; +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup; + //! Elliptic Curve over GF(p), where p is prime -class ECP : public AbstractGroup +class CRYPTOPP_DLL ECP : public AbstractGroup { public: typedef ModularArithmetic Field; @@ -77,12 +79,18 @@ public: const FieldElement & GetA() const {return m_a;} const FieldElement & GetB() const {return m_b;} + bool operator==(const ECP &rhs) const + {return GetField() == rhs.GetField() && m_a == rhs.m_a && m_b == rhs.m_b;} + private: clonable_ptr m_fieldPtr; FieldElement m_a, m_b; mutable Point m_R; }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation; + template class EcPrecomputation; //! . @@ -102,7 +110,11 @@ public: void DEREncodeElement(BufferedTransformation &bt, const Element &v) const {m_ec->DEREncodePoint(bt, v, false);} // non-inherited - void SetCurve(const ECP &ec); + void SetCurve(const ECP &ec) + { + m_ec.reset(new ECP(ec, true)); + m_ecOriginal = ec; + } const ECP & GetCurve() const {return *m_ecOriginal;} private: diff --git a/eprecomp.cpp b/eprecomp.cpp index f9878b90..a061cf6c 100644 --- a/eprecomp.cpp +++ b/eprecomp.cpp @@ -1,6 +1,9 @@ // eprecomp.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "eprecomp.h" #include "asn.h" @@ -105,3 +108,5 @@ template T } NAMESPACE_END + +#endif diff --git a/files.cpp b/files.cpp index fc32b4b4..25300a1b 100644 --- a/files.cpp +++ b/files.cpp @@ -1,6 +1,9 @@ // files.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "files.h" NAMESPACE_BEGIN(CryptoPP) @@ -16,16 +19,15 @@ void Files_TestInstantiations() void FileStore::StoreInitialize(const NameValuePairs ¶meters) { - m_file.close(); - m_file.clear(); + m_file.reset(new std::ifstream); const char *fileName; if (parameters.GetValue(Name::InputFileName(), fileName)) { ios::openmode binary = parameters.GetValueWithDefault(Name::InputBinaryMode(), true) ? ios::binary : ios::openmode(0); - m_file.open(fileName, ios::in | binary); - if (!m_file) + m_file->open(fileName, ios::in | binary); + if (!*m_file) throw OpenErr(fileName); - m_stream = &m_file; + m_stream = m_file.get(); } else { @@ -148,14 +150,15 @@ unsigned long FileStore::Skip(unsigned long skipMax) void FileSink::IsolatedInitialize(const NameValuePairs ¶meters) { + m_file.reset(new std::ofstream); const char *fileName; if (parameters.GetValue(Name::OutputFileName(), fileName)) { ios::openmode binary = parameters.GetValueWithDefault(Name::OutputBinaryMode(), true) ? ios::binary : ios::openmode(0); - m_file.open(fileName, ios::out | ios::trunc | binary); - if (!m_file) + m_file->open(fileName, ios::out | ios::trunc | binary); + if (!*m_file) throw OpenErr(fileName); - m_stream = &m_file; + m_stream = m_file.get(); } else { @@ -193,3 +196,5 @@ unsigned int FileSink::Put2(const byte *inString, unsigned int length, int messa } NAMESPACE_END + +#endif diff --git a/files.h b/files.h index fc3d650b..e54d8902 100644 --- a/files.h +++ b/files.h @@ -11,7 +11,7 @@ NAMESPACE_BEGIN(CryptoPP) //! . -class FileStore : public Store, private FilterPutSpaceHelper +class CRYPTOPP_DLL FileStore : public Store, private FilterPutSpaceHelper, public NotCopyable { public: class Err : public Exception @@ -38,7 +38,7 @@ public: private: void StoreInitialize(const NameValuePairs ¶meters); - std::ifstream m_file; + member_ptr m_file; std::istream *m_stream; byte *m_space; unsigned int m_len; @@ -46,7 +46,7 @@ private: }; //! . -class FileSource : public SourceTemplate +class CRYPTOPP_DLL FileSource : public SourceTemplate { public: typedef FileStore::Err Err; @@ -64,7 +64,7 @@ public: }; //! . -class FileSink : public Sink +class CRYPTOPP_DLL FileSink : public Sink, public NotCopyable { public: class Err : public Exception @@ -88,7 +88,7 @@ public: bool IsolatedFlush(bool hardFlush, bool blocking); private: - std::ofstream m_file; + member_ptr m_file; std::ostream *m_stream; }; diff --git a/filters.cpp b/filters.cpp index 576022e3..3596e26f 100644 --- a/filters.cpp +++ b/filters.cpp @@ -1,6 +1,9 @@ // filters.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "filters.h" #include "mqueue.h" #include "fltrimpl.h" @@ -154,7 +157,7 @@ unsigned int MeterFilter::Put2(const byte *begin, unsigned int length, int messa m_currentSeriesMessages++; m_totalMessages++; } - + FILTER_OUTPUT(1, begin, length, messageEnd); FILTER_END_NO_MESSAGE_END; } @@ -773,7 +776,7 @@ void SignatureVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameV { m_flags = parameters.GetValueWithDefault(Name::SignatureVerificationFilterFlags(), (word32)DEFAULT_FLAGS); m_messageAccumulator.reset(m_verifier.NewVerificationAccumulator()); - unsigned int size = m_verifier.SignatureLength(); + unsigned int size = m_verifier.SignatureLength(); assert(size != 0); // TODO: handle recoverable signature scheme m_verified = false; firstSize = m_flags & SIGNATURE_AT_BEGIN ? size : 0; @@ -931,3 +934,5 @@ unsigned int NullStore::TransferTo2(BufferedTransformation &target, unsigned lon } NAMESPACE_END + +#endif diff --git a/filters.h b/filters.h index afd33572..74b2b3d3 100644 --- a/filters.h +++ b/filters.h @@ -11,7 +11,7 @@ NAMESPACE_BEGIN(CryptoPP) /// provides an implementation of BufferedTransformation's attachment interface -class CRYPTOPP_NO_VTABLE Filter : public BufferedTransformation, public NotCopyable +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Filter : public BufferedTransformation, public NotCopyable { public: Filter(BufferedTransformation *attachment); @@ -52,7 +52,7 @@ protected: int m_continueAt; }; -struct FilterPutSpaceHelper +struct CRYPTOPP_DLL FilterPutSpaceHelper { // desiredSize is how much to ask target, bufferSize is how much to allocate in m_tempSpace byte *HelpCreatePutSpace(BufferedTransformation &target, const std::string &channel, unsigned int minSize, unsigned int desiredSize, unsigned int &bufferSize) @@ -80,7 +80,7 @@ struct FilterPutSpaceHelper }; //! measure how many byte and messages pass through, also serves as valve -class MeterFilter : public Bufferless +class CRYPTOPP_DLL MeterFilter : public Bufferless { public: MeterFilter(BufferedTransformation *attachment=NULL, bool transparent=true) @@ -111,14 +111,14 @@ private: }; //! . -class TransparentFilter : public MeterFilter +class CRYPTOPP_DLL TransparentFilter : public MeterFilter { public: TransparentFilter(BufferedTransformation *attachment=NULL) : MeterFilter(attachment, true) {} }; //! . -class OpaqueFilter : public MeterFilter +class CRYPTOPP_DLL OpaqueFilter : public MeterFilter { public: OpaqueFilter(BufferedTransformation *attachment=NULL) : MeterFilter(attachment, false) {} @@ -129,7 +129,7 @@ public: First and last blocks are optional, and middle blocks may be a stream instead (i.e. blockSize == 1). */ -class FilterWithBufferedInput : public Filter +class CRYPTOPP_DLL FilterWithBufferedInput : public Filter { public: FilterWithBufferedInput(BufferedTransformation *attachment); @@ -212,7 +212,7 @@ private: }; //! . -class FilterWithInputQueue : public Filter +class CRYPTOPP_DLL FilterWithInputQueue : public Filter { public: FilterWithInputQueue(BufferedTransformation *attachment) : Filter(attachment) {} @@ -238,7 +238,7 @@ protected: }; //! Filter Wrapper for StreamTransformation -class StreamTransformationFilter : public FilterWithBufferedInput, private FilterPutSpaceHelper +class CRYPTOPP_DLL StreamTransformationFilter : public FilterWithBufferedInput, private FilterPutSpaceHelper { public: enum BlockPaddingScheme {NO_PADDING, ZEROS_PADDING, PKCS_PADDING, ONE_AND_ZEROS_PADDING, DEFAULT_PADDING}; @@ -265,7 +265,7 @@ typedef StreamTransformationFilter StreamCipherFilter; #endif //! Filter Wrapper for HashTransformation -class HashFilter : public Bufferless, private FilterPutSpaceHelper +class CRYPTOPP_DLL HashFilter : public Bufferless, private FilterPutSpaceHelper { public: HashFilter(HashTransformation &hm, BufferedTransformation *attachment = NULL, bool putMessage=false) @@ -283,7 +283,7 @@ private: }; //! Filter Wrapper for HashTransformation -class HashVerificationFilter : public FilterWithBufferedInput +class CRYPTOPP_DLL HashVerificationFilter : public FilterWithBufferedInput { public: class HashVerificationFailed : public Exception @@ -317,7 +317,7 @@ private: typedef HashVerificationFilter HashVerifier; // for backwards compatibility //! Filter Wrapper for PK_Signer -class SignerFilter : public Unflushable +class CRYPTOPP_DLL SignerFilter : public Unflushable { public: SignerFilter(RandomNumberGenerator &rng, const PK_Signer &signer, BufferedTransformation *attachment = NULL, bool putMessage=false) @@ -328,14 +328,14 @@ public: private: RandomNumberGenerator &m_rng; - const PK_Signer &m_signer; + const PK_Signer &m_signer; member_ptr m_messageAccumulator; bool m_putMessage; SecByteBlock m_buf; }; //! Filter Wrapper for PK_Verifier -class SignatureVerificationFilter : public FilterWithBufferedInput +class CRYPTOPP_DLL SignatureVerificationFilter : public FilterWithBufferedInput { public: class SignatureVerificationFailed : public Exception @@ -364,10 +364,10 @@ private: bool m_verified; }; -typedef SignatureVerificationFilter VerifierFilter; // for backwards compatibility +typedef SignatureVerificationFilter VerifierFilter; // for backwards compatibility //! Redirect input to another BufferedTransformation without owning it -class Redirector : public CustomSignalPropagation +class CRYPTOPP_DLL Redirector : public CustomSignalPropagation { public: enum Behavior @@ -429,7 +429,7 @@ private: }; // Used By ProxyFilter -class OutputProxy : public CustomSignalPropagation +class CRYPTOPP_DLL OutputProxy : public CustomSignalPropagation { public: OutputProxy(BufferedTransformation &owner, bool passSignal) : m_owner(owner), m_passSignal(passSignal) {} @@ -467,7 +467,7 @@ private: }; //! Base class for Filter classes that are proxies for a chain of other filters. -class ProxyFilter : public FilterWithBufferedInput +class CRYPTOPP_DLL ProxyFilter : public FilterWithBufferedInput { public: ProxyFilter(BufferedTransformation *filter, unsigned int firstSize, unsigned int lastSize, BufferedTransformation *attachment); @@ -483,7 +483,7 @@ protected: }; //! simple proxy filter that doesn't modify the underlying filter's input or output -class SimpleProxyFilter : public ProxyFilter +class CRYPTOPP_DLL SimpleProxyFilter : public ProxyFilter { public: SimpleProxyFilter(BufferedTransformation *filter, BufferedTransformation *attachment) @@ -495,7 +495,7 @@ public: //! proxy for the filter created by PK_Encryptor::CreateEncryptionFilter /*! This class is here just to provide symmetry with VerifierFilter. */ -class PK_EncryptorFilter : public SimpleProxyFilter +class CRYPTOPP_DLL PK_EncryptorFilter : public SimpleProxyFilter { public: PK_EncryptorFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment = NULL) @@ -504,7 +504,7 @@ public: //! proxy for the filter created by PK_Decryptor::CreateDecryptionFilter /*! This class is here just to provide symmetry with SignerFilter. */ -class PK_DecryptorFilter : public SimpleProxyFilter +class CRYPTOPP_DLL PK_DecryptorFilter : public SimpleProxyFilter { public: PK_DecryptorFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment = NULL) @@ -532,7 +532,7 @@ public: typename T::size_type size = m_output->size(); if (length < size && size + length > m_output->capacity()) m_output->reserve(2*size); - m_output->append((const char_type *)begin, (const char_type *)begin+length); + m_output->append((const char_type *)begin, (const char_type *)begin+length); } return 0; } @@ -542,10 +542,11 @@ private: }; //! Append input to an std::string +CRYPTOPP_DLL_TEMPLATE_CLASS StringSinkTemplate; typedef StringSinkTemplate StringSink; //! Copy input to a memory buffer -class ArraySink : public Bufferless +class CRYPTOPP_DLL ArraySink : public Bufferless { public: ArraySink(const NameValuePairs ¶meters = g_nullNameValuePairs) {IsolatedInitialize(parameters);} @@ -565,7 +566,7 @@ protected: }; //! Xor input to a memory buffer -class ArrayXorSink : public ArraySink +class CRYPTOPP_DLL ArrayXorSink : public ArraySink { public: ArrayXorSink(byte *buf, unsigned int size) @@ -586,18 +587,18 @@ public: template StringStore(const T &string) {StoreInitialize(MakeParameters("InputBuffer", ConstByteArrayParameter(string)));} - unsigned int TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel=NULL_CHANNEL, bool blocking=true); - unsigned int CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end=ULONG_MAX, const std::string &channel=NULL_CHANNEL, bool blocking=true) const; + CRYPTOPP_DLL unsigned int TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel=NULL_CHANNEL, bool blocking=true); + CRYPTOPP_DLL unsigned int CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end=ULONG_MAX, const std::string &channel=NULL_CHANNEL, bool blocking=true) const; private: - void StoreInitialize(const NameValuePairs ¶meters); + CRYPTOPP_DLL void StoreInitialize(const NameValuePairs ¶meters); const byte *m_store; unsigned int m_length, m_count; }; //! . -class RandomNumberStore : public Store +class CRYPTOPP_DLL RandomNumberStore : public Store { public: RandomNumberStore(RandomNumberGenerator &rng, unsigned long length) @@ -621,7 +622,7 @@ private: }; //! . -class NullStore : public Store +class CRYPTOPP_DLL NullStore : public Store { public: NullStore(unsigned long size = ULONG_MAX) : m_size(size) {} @@ -635,7 +636,7 @@ private: }; //! A Filter that pumps data into its attachment as input -class CRYPTOPP_NO_VTABLE Source : public InputRejecting +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Source : public InputRejecting { public: Source(BufferedTransformation *attachment) @@ -690,7 +691,7 @@ protected: }; //! . -class StringSource : public SourceTemplate +class CRYPTOPP_DLL StringSource : public SourceTemplate { public: StringSource(BufferedTransformation *attachment = NULL) @@ -699,17 +700,12 @@ public: : SourceTemplate(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string)));} StringSource(const byte *string, unsigned int length, bool pumpAll, BufferedTransformation *attachment = NULL) : SourceTemplate(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string, length)));} - -#ifdef __MWERKS__ // CW60 workaround StringSource(const std::string &string, bool pumpAll, BufferedTransformation *attachment = NULL) -#else - template StringSource(const T &string, bool pumpAll, BufferedTransformation *attachment = NULL) -#endif : SourceTemplate(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string)));} }; //! . -class RandomNumberSource : public SourceTemplate +class CRYPTOPP_DLL RandomNumberSource : public SourceTemplate { public: RandomNumberSource(RandomNumberGenerator &rng, unsigned int length, bool pumpAll, BufferedTransformation *attachment = NULL) diff --git a/fips140.cpp b/fips140.cpp index 7781956a..1fcf5901 100644 --- a/fips140.cpp +++ b/fips140.cpp @@ -1,6 +1,9 @@ // fips140.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "fips140.h" #include "trdlocal.h" // needs to be included last for cygwin @@ -32,7 +35,7 @@ void SimulatePowerUpSelfTestFailure() g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_FAILED; } -PowerUpSelfTestStatus GetPowerUpSelfTestStatus() +PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus() { return g_powerUpSelfTestStatus; } @@ -77,3 +80,5 @@ void SignaturePairwiseConsistencyTest_FIPS_140_Only(const PK_Signer &signer, con } NAMESPACE_END + +#endif diff --git a/fips140.h b/fips140.h index 76353ed5..f46eff69 100644 --- a/fips140.h +++ b/fips140.h @@ -10,26 +10,36 @@ NAMESPACE_BEGIN(CryptoPP) //! exception thrown when a crypto algorithm is used after a self test fails -class SelfTestFailure : public Exception +class CRYPTOPP_DLL SelfTestFailure : public Exception { public: explicit SelfTestFailure(const std::string &s) : Exception(OTHER_ERROR, s) {} }; //! returns whether FIPS 140-2 compliance features were enabled at compile time -bool FIPS_140_2_ComplianceEnabled(); +CRYPTOPP_DLL bool FIPS_140_2_ComplianceEnabled(); //! enum values representing status of the power-up self test enum PowerUpSelfTestStatus {POWER_UP_SELF_TEST_NOT_DONE, POWER_UP_SELF_TEST_FAILED, POWER_UP_SELF_TEST_PASSED}; //! perform the power-up self test, and set the self test status -void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha1Digest); +CRYPTOPP_DLL void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleMac); //! set the power-up self test status to POWER_UP_SELF_TEST_FAILED -void SimulatePowerUpSelfTestFailure(); +CRYPTOPP_DLL void SimulatePowerUpSelfTestFailure(); //! return the current power-up self test status -PowerUpSelfTestStatus GetPowerUpSelfTestStatus(); +CRYPTOPP_DLL PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus(); + +typedef PowerUpSelfTestStatus (CRYPTOPP_API * PGetPowerUpSelfTestStatus)(); + +CRYPTOPP_DLL const byte * CRYPTOPP_API GetActualMacAndLocation(unsigned int &macSize, unsigned int &fileLocation); + +typedef const byte * (CRYPTOPP_API * PGetActualMacAndLocation)(unsigned int &macSize, unsigned int &fileLocation); + +CRYPTOPP_DLL MessageAuthenticationCode * NewIntegrityCheckingMAC(); + +CRYPTOPP_DLL bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac = NULL, unsigned long *pMacFileLocation = NULL); // this is used by Algorithm constructor to allow Algorithm objects to be constructed for the self test bool PowerUpSelfTestInProgressOnThisThread(); diff --git a/fipstest.cpp b/fipstest.cpp index c2256193..70fbb87e 100644 --- a/fipstest.cpp +++ b/fipstest.cpp @@ -1,27 +1,24 @@ // fipstest.cpp - written and placed in the public domain by Wei Dai #include "pch.h" -#include "fips140.h" -#include "sha.h" -#include "files.h" -#include "hex.h" -#include "rsa.h" -#include "dsa.h" -#include "mqueue.h" -#include "channels.h" -#include "osrng.h" -#include "des.h" -#include "eccrypto.h" -#include "ec2n.h" -#include "ecp.h" -#include "modes.h" -#include "aes.h" -#include "skipjack.h" -#include "trdlocal.h" // needs to be included last for cygwin + +#ifndef CRYPTOPP_IMPORTS + +#include "dll.h" +#include NAMESPACE_BEGIN(CryptoPP) extern PowerUpSelfTestStatus g_powerUpSelfTestStatus; +SecByteBlock g_actualMac; +unsigned long g_macFileLocation = 0; + +const byte * CRYPTOPP_API GetActualMacAndLocation(unsigned int &macSize, unsigned int &fileLocation) +{ + macSize = g_actualMac.size(); + fileLocation = g_macFileLocation; + return g_actualMac; +} void KnownAnswerTest(RandomNumberGenerator &rng, const char *output) { @@ -105,22 +102,22 @@ void SymmetricEncryptionKnownAnswerTest( void KnownAnswerTest(HashTransformation &hash, const char *message, const char *digest) { EqualityComparisonFilter comparison; - StringSource(message, true, new HashFilter(hash, new ChannelSwitch(comparison, "0"))); StringSource(digest, true, new HexDecoder(new ChannelSwitch(comparison, "1"))); + StringSource(message, true, new HashFilter(hash, new ChannelSwitch(comparison, "0"))); comparison.ChannelMessageSeriesEnd("0"); comparison.ChannelMessageSeriesEnd("1"); } template -void SecureHashKnownAnswerTest(const char *message, const char *digest) +void SecureHashKnownAnswerTest(const char *message, const char *digest, HASH *dummy = NULL) { HASH hash; KnownAnswerTest(hash, message, digest); } template -void MAC_KnownAnswerTest(const char *key, const char *message, const char *digest) +void MAC_KnownAnswerTest(const char *key, const char *message, const char *digest, MAC *dummy = NULL) { std::string decodedKey; StringSource(key, true, new HexDecoder(new StringSink(decodedKey))); @@ -219,7 +216,104 @@ void SignaturePairwiseConsistencyTest(const char *key, SCHEME *dummy = NULL) SignaturePairwiseConsistencyTest(signer, verifier); } -void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha1Digest) +MessageAuthenticationCode * NewIntegrityCheckingMAC() +{ + byte key[] = {0x47, 0x1E, 0x33, 0x96, 0x65, 0xB1, 0x6A, 0xED, 0x0B, 0xF8, 0x6B, 0xFD, 0x01, 0x65, 0x05, 0xCC}; + return new HMAC(key, sizeof(key)); +} + +bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) +{ + std::auto_ptr mac(NewIntegrityCheckingMAC()); + unsigned int macSize = mac->DigestSize(); + + SecByteBlock tempMac; + SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; + actualMac.resize(macSize); + + unsigned long tempLocation; + unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; + macFileLocation = 0; + + HashFilter verifier(*mac, new ArraySink(actualMac, actualMac.size())); + FileStore file(moduleFilename); + +#ifdef CRYPTOPP_WIN32_AVAILABLE + // try to hash from memory first + HMODULE h = GetModuleHandle(moduleFilename); + IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)h; + IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)((byte *)h + ph->e_lfanew); + IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); + DWORD nSections = phnt->FileHeader.NumberOfSections; + DWORD currentFilePos = 0; + + while (nSections--) + { + switch (phs->Characteristics) + { + default: + break; + case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: + case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: + DWORD sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); + const byte *memStart = (const byte *)h + phs->VirtualAddress; + DWORD fileStart = phs->PointerToRawData; + if (phs->VirtualAddress == phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress) + { + // read IAT, which is changed during DLL loading, from disk + DWORD iatSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size; + fileStart += iatSize; + memStart += iatSize; + sectionSize -= iatSize; + } + file.TransferTo(verifier, fileStart - currentFilePos); + if (memStart <= expectedModuleMac && expectedModuleMac < memStart + sectionSize) + { + // skip over the MAC + verifier.Put(memStart, expectedModuleMac - memStart); + verifier.Put(expectedModuleMac + macSize, sectionSize - macSize - (expectedModuleMac - memStart)); + macFileLocation = fileStart + (expectedModuleMac - memStart); + } + else + verifier.Put(memStart, sectionSize); + ::VirtualUnlock((LPVOID)memStart, sectionSize); // release the memory from working set + file.Skip(sectionSize); + currentFilePos = fileStart + sectionSize; + } + phs++; + } +#endif + file.TransferAllTo(verifier); + +#ifdef CRYPTOPP_WIN32_AVAILABLE + // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), + // hash from disk instead + if (memcmp(expectedModuleMac, actualMac, macSize) != 0) + { + OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); + file.Initialize(MakeParameters("InputFileName", moduleFilename)); + verifier.Detach(new ArraySink(actualMac, actualMac.size())); + if (macFileLocation) + { + file.TransferTo(verifier, macFileLocation); + file.Skip(macSize); + } + file.TransferAllTo(verifier); + } +#endif + + if (memcmp(expectedModuleMac, actualMac, macSize) == 0) + return true; + +#ifdef CRYPTOPP_WIN32_AVAILABLE + std::string hexMac; + HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); + OutputDebugString((moduleFilename + (" integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); +#endif + return false; +} + +void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleMac) { g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_NOT_DONE; SetPowerUpSelfTestInProgressOnThisThread(true); @@ -228,72 +322,8 @@ void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha { if (FIPS_140_2_ComplianceEnabled() || moduleFilename != NULL) { - // integrity test - SHA1 sha; - HashVerifier verifier(sha); - verifier.Put(expectedModuleSha1Digest, sha.DigestSize()); - FileStore file(moduleFilename); - -#ifdef CRYPTOPP_WIN32_AVAILABLE - // try to hash from memory first - HMODULE h = GetModuleHandle(moduleFilename); - IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)h; - IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)((byte *)h + ph->e_lfanew); - IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); - DWORD nSections = phnt->FileHeader.NumberOfSections; - DWORD currentFilePos = 0; - - while (nSections--) - { - DWORD sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); - switch (phs->Characteristics) - { - default: - break; - case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: - case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: - const byte *memStart = (const byte *)h + phs->VirtualAddress; - DWORD fileStart = phs->PointerToRawData; - if (phs->VirtualAddress == phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress) - { - // read IAT, which is changed during DLL loading, from disk - DWORD iatSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].Size; - fileStart += iatSize; - memStart += iatSize; - sectionSize -= iatSize; - } - file.TransferTo(verifier, fileStart - currentFilePos); - verifier.Put(memStart, sectionSize); - ::VirtualUnlock((LPVOID)memStart, sectionSize); // release the memory from working set - file.Skip(sectionSize); - currentFilePos = fileStart + sectionSize; - } - phs++; - } -#endif - file.TransferAllTo(verifier); - -#ifdef CRYPTOPP_WIN32_AVAILABLE - // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), - // hash from disk instead - if (!verifier.GetLastResult()) - { - OutputDebugString("In memory EDC test failed. This may be caused by debug breakpoints or DLL relocation.\n"); - verifier.Put(expectedModuleSha1Digest, sha.DigestSize()); - file.Initialize(MakeParameters(Name::InputFileName(), moduleFilename)); - file.TransferAllTo(verifier); - } -#endif - - if (!verifier.GetLastResult()) - { -#ifdef CRYPTOPP_WIN32_AVAILABLE - std::string actualDigest; - FileSource(moduleFilename, true, new HashFilter(sha, new HexEncoder(new StringSink(actualDigest)))); - OutputDebugString(("Crypto++ EDC test failed. Actual digest is: " + actualDigest + "\n").c_str()); -#endif + if (!IntegrityCheckModule(moduleFilename, expectedModuleMac, &g_actualMac, &g_macFileLocation)) throw 0; // throw here so we break in the debugger, this will be caught right away - } } // algorithm tests @@ -359,11 +389,38 @@ void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha "abc", "A9993E364706816ABA3E25717850C26C9CD0D89D"); + SecureHashKnownAnswerTest( + "abc", + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + + SecureHashKnownAnswerTest( + "abc", + "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"); + + SecureHashKnownAnswerTest( + "abc", + "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"); + MAC_KnownAnswerTest >( "303132333435363738393a3b3c3d3e3f40414243", "Sample #2", "0922d3405faa3d194f82a45830737d5cc6c75d24"); + MAC_KnownAnswerTest >( + "303132333435363738393a3b3c3d3e3f40414243", + "abc", + "D28363F335B2DAE468793A38680DEA9F7FB8BE1DCEDA197CDB3B1CB59A9F6422"); + + MAC_KnownAnswerTest >( + "303132333435363738393a3b3c3d3e3f40414243", + "abc", + "E7740C592F1414C969190EFACF51FC8BE1CB52F5DC5E686200D2CA1773D151DB19C59112371CE374165A6BF72AEF69D0"); + + MAC_KnownAnswerTest >( + "303132333435363738393a3b3c3d3e3f40414243", + "abc", + "BF07864E733B995862F3C2D432C7FF2F5EB073FFFC4F880CD94D5D21086476B7428F27BE694A9D9CB3BB500FE1255852BAFCBAF4042390B3706CDF02421B51AC"); + SignatureKnownAnswerTest >( "30820150020100300d06092a864886f70d01010105000482013a3082013602010002400a66791dc6988168de7ab77419bb7fb0" "c001c62710270075142942e19a8d8c51d053b3e3782a1de5dc5af4ebe99468170114a1dfe67cdc9a9af55d655620bbab0203010001" @@ -398,3 +455,5 @@ done: } NAMESPACE_END + +#endif diff --git a/gf2n.cpp b/gf2n.cpp index 30430750..b7b4bf9c 100644 --- a/gf2n.cpp +++ b/gf2n.cpp @@ -1,17 +1,18 @@ // gf2n.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "gf2n.h" #include "algebra.h" #include "words.h" -#include "rng.h" +#include "randpool.h" #include "asn.h" #include "oids.h" #include -#include "algebra.cpp" - NAMESPACE_BEGIN(CryptoPP) PolynomialMod2::PolynomialMod2() @@ -551,10 +552,10 @@ GF2NP::Element GF2NP::SolveQuadraticEquation(const Element &a) const if (m%2 == 0) { Element z, w; + RandomPool rng; do { - LC_RNG rng(11111); - Element p(rng, m); + Element p((RandomNumberGenerator &)rng, m); z = PolynomialMod2::Zero(); w = p; for (unsigned int i=1; i<=m-1; i++) @@ -868,3 +869,5 @@ GF2NP * BERDecodeGF2NP(BufferedTransformation &bt) } NAMESPACE_END + +#endif diff --git a/gf2n.h b/gf2n.h index 69a149b7..f5a4468c 100644 --- a/gf2n.h +++ b/gf2n.h @@ -14,7 +14,7 @@ NAMESPACE_BEGIN(CryptoPP) //! Polynomial with Coefficients in GF(2) /*! \nosubgrouping */ -class PolynomialMod2 +class CRYPTOPP_DLL PolynomialMod2 { public: //! \name ENUMS, EXCEPTIONS, and TYPEDEFS @@ -236,8 +236,13 @@ private: SecWordBlock reg; }; +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup; +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing; +CRYPTOPP_DLL_TEMPLATE_CLASS EuclideanDomainOf; +CRYPTOPP_DLL_TEMPLATE_CLASS QuotientRing >; + //! GF(2^n) with Polynomial Basis -class GF2NP : public QuotientRing > +class CRYPTOPP_DLL GF2NP : public QuotientRing > { public: GF2NP(const PolynomialMod2 &modulus); @@ -273,7 +278,7 @@ protected: }; //! GF(2^n) with Trinomial Basis -class GF2NT : public GF2NP +class CRYPTOPP_DLL GF2NT : public GF2NP { public: // polynomial modulus = x^t0 + x^t1 + x^t2, t0 > t1 > t2 @@ -297,7 +302,7 @@ private: }; //! GF(2^n) with Pentanomial Basis -class GF2NPP : public GF2NP +class CRYPTOPP_DLL GF2NPP : public GF2NP { public: // polynomial modulus = x^t0 + x^t1 + x^t2 + x^t3 + x^t4, t0 > t1 > t2 > t3 > t4 @@ -312,7 +317,7 @@ private: }; // construct new GF2NP from the ASN.1 sequence Characteristic-two -GF2NP * BERDecodeGF2NP(BufferedTransformation &bt); +CRYPTOPP_DLL GF2NP * BERDecodeGF2NP(BufferedTransformation &bt); //! inline bool operator==(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) diff --git a/gfpcrypt.cpp b/gfpcrypt.cpp index c27a9671..eae4f0d5 100644 --- a/gfpcrypt.cpp +++ b/gfpcrypt.cpp @@ -1,6 +1,9 @@ // dsa.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "gfpcrypt.h" #include "asn.h" #include "oids.h" @@ -265,3 +268,5 @@ unsigned int DL_GroupParameters_IntegerBased::GetDefaultSubgroupOrderSize(unsign } NAMESPACE_END + +#endif diff --git a/gfpcrypt.h b/gfpcrypt.h index 5cf2492d..f3f5870e 100644 --- a/gfpcrypt.h +++ b/gfpcrypt.h @@ -17,8 +17,10 @@ NAMESPACE_BEGIN(CryptoPP) +CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters; + //! . -class CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public DL_GroupParameters, public ASN1CryptoMaterial +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public DL_GroupParameters, public ASN1CryptoMaterial { typedef DL_GroupParameters_IntegerBased ThisClass; @@ -110,8 +112,10 @@ public: {return !operator==(rhs);} }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_IntegerBasedImpl; + //! . -class DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl +class CRYPTOPP_DLL DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl { public: // DL_GroupParameters @@ -133,7 +137,7 @@ protected: }; //! . -class DL_GroupParameters_GFP_DefaultSafePrime : public DL_GroupParameters_GFP +class CRYPTOPP_DLL DL_GroupParameters_GFP_DefaultSafePrime : public DL_GroupParameters_GFP { public: typedef NoCofactorMultiplication DefaultCofactorOption; @@ -172,6 +176,8 @@ public: } }; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA; + //! . template class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm @@ -179,11 +185,6 @@ class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm public: static const char * StaticAlgorithmName() {return "NR";} - Integer EncodeDigest(unsigned int modulusBits, const byte *digest, unsigned int digestLen) const - { - return NR_EncodeDigest(modulusBits, digest, digestLen); - } - void Sign(const DL_GroupParameters ¶ms, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const { const Integer &q = params.GetSubgroupOrder(); @@ -359,7 +360,7 @@ struct NR : public DL_SS< }; //! . -class DL_GroupParameters_DSA : public DL_GroupParameters_GFP +class CRYPTOPP_DLL DL_GroupParameters_DSA : public DL_GroupParameters_GFP { public: /*! also checks that the lengths of p and q are allowed by the DSA standard */ @@ -371,6 +372,10 @@ public: struct DSA; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_GFP; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_GFP; +CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest, DSA>; + //! . struct DL_Keys_DSA { @@ -379,7 +384,7 @@ struct DL_Keys_DSA }; //! DSA -struct DSA : public DL_SS< +struct CRYPTOPP_DLL DSA : public DL_SS< DL_Keys_DSA, DL_Algorithm_GDSA, DL_SignatureMessageEncodingMethod_DSA, diff --git a/gost.h b/gost.h index b8f5b1e3..2bfe4c00 100644 --- a/gost.h +++ b/gost.h @@ -17,7 +17,7 @@ struct GOST_Info : public FixedBlockSize<8>, public FixedKeyLength<32> /// GOST class GOST : public GOST_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -45,8 +45,8 @@ class GOST : public GOST_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef GOST::Encryption GOSTEncryption; diff --git a/haval.cpp b/haval.cpp index 75414704..ff495e7d 100644 --- a/haval.cpp +++ b/haval.cpp @@ -7,9 +7,10 @@ NAMESPACE_BEGIN(CryptoPP) HAVAL::HAVAL(unsigned int digestSize, unsigned int pass) - : IteratedHash(DIGESTSIZE) - , digestSize(digestSize), pass(pass) + : digestSize(digestSize), pass(pass) { + SetStateSize(DIGESTSIZE); + if (!(digestSize >= 16 && digestSize <= 32 && digestSize%4==0)) throw InvalidArgument("HAVAL: invalid digest size"); @@ -31,7 +32,7 @@ void HAVAL::Init() m_digest[7] = 0xEC4E6C89; } -void HAVAL::vTransform(const word32 *in) +void HAVAL::HashEndianCorrectedBlock(const word32 *in) { if (pass==3) HAVAL3::Transform(m_digest, in); @@ -53,7 +54,7 @@ void HAVAL::TruncatedFinal(byte *hash, unsigned int size) m_data[30] = GetBitCountLo(); m_data[31] = GetBitCountHi(); - vTransform(m_data); + HashEndianCorrectedBlock(m_data); Tailor(digestSize*8); CorrectEndianess(m_digest, m_digest, digestSize); memcpy(hash, m_digest, size); diff --git a/haval.h b/haval.h index 35c6a192..a5aa3f57 100644 --- a/haval.h +++ b/haval.h @@ -23,7 +23,7 @@ protected: void Init(); void Tailor(unsigned int FPTLEN); - void vTransform(const word32 *in); + void HashEndianCorrectedBlock(const word32 *in); const unsigned int digestSize, pass; }; diff --git a/hex.cpp b/hex.cpp index fb653794..5ac6e8cf 100644 --- a/hex.cpp +++ b/hex.cpp @@ -1,6 +1,9 @@ // hex.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "hex.h" NAMESPACE_BEGIN(CryptoPP) @@ -30,3 +33,5 @@ const int *HexDecoder::GetDecodingLookupArray() } NAMESPACE_END + +#endif diff --git a/hex.h b/hex.h index 85cdaa8a..ec8c91c0 100644 --- a/hex.h +++ b/hex.h @@ -6,7 +6,7 @@ NAMESPACE_BEGIN(CryptoPP) //! Converts given data to base 16 -class HexEncoder : public SimpleProxyFilter +class CRYPTOPP_DLL HexEncoder : public SimpleProxyFilter { public: HexEncoder(BufferedTransformation *attachment = NULL, bool uppercase = true, int outputGroupSize = 0, const std::string &separator = ":", const std::string &terminator = "") @@ -19,7 +19,7 @@ public: }; //! Decode base 16 data back to bytes -class HexDecoder : public BaseN_Decoder +class CRYPTOPP_DLL HexDecoder : public BaseN_Decoder { public: HexDecoder(BufferedTransformation *attachment = NULL) diff --git a/hmac.cpp b/hmac.cpp new file mode 100644 index 00000000..6fb9a028 --- /dev/null +++ b/hmac.cpp @@ -0,0 +1,84 @@ +// hmac.cpp - written and placed in the public domain by Wei Dai + +#include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + +#include "hmac.h" + +NAMESPACE_BEGIN(CryptoPP) + +void HMAC_Base::UncheckedSetKey(const byte *userKey, unsigned int keylength) +{ + AssertValidKeyLength(keylength); + + Restart(); + + HashTransformation &hash = AccessHash(); + unsigned int blockSize = hash.BlockSize(); + + if (!blockSize) + throw InvalidArgument("HMAC: can only be used with a block-based hash function"); + + if (keylength <= blockSize) + memcpy(AccessIpad(), userKey, keylength); + else + { + AccessHash().CalculateDigest(AccessIpad(), userKey, keylength); + keylength = hash.DigestSize(); + } + + assert(keylength <= blockSize); + memset(AccessIpad()+keylength, 0, blockSize-keylength); + + for (unsigned int i=0; i -class CRYPTOPP_NO_VTABLE HMAC_Base : public VariableKeyLength<16, 0, UINT_MAX>, public MessageAuthenticationCode +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HMAC_Base : public VariableKeyLength<16, 0, UINT_MAX>, public MessageAuthenticationCode { public: - static std::string StaticAlgorithmName() {return std::string("HMAC(") + T::StaticAlgorithmName() + ")";} - - // put enums here for Metrowerks 4 - enum {DIGESTSIZE=T::DIGESTSIZE, BLOCKSIZE=T::BLOCKSIZE}; - HMAC_Base() : m_innerHashKeyed(false) {} void UncheckedSetKey(const byte *userKey, unsigned int keylength); void Restart(); void Update(const byte *input, unsigned int length); void TruncatedFinal(byte *mac, unsigned int size); - unsigned int DigestSize() const {return DIGESTSIZE;} + unsigned int OptimalBlockSize() const {return const_cast(this)->AccessHash().OptimalBlockSize();} + unsigned int DigestSize() const {return const_cast(this)->AccessHash().DigestSize();} + +protected: + virtual HashTransformation & AccessHash() =0; + virtual byte * AccessIpad() =0; + virtual byte * AccessOpad() =0; + virtual byte * AccessInnerHash() =0; private: void KeyInnerHash(); enum {IPAD=0x36, OPAD=0x5c}; - FixedSizeSecBlock k_ipad, k_opad; - FixedSizeSecBlock m_innerHash; - T m_hash; bool m_innerHashKeyed; }; //! HMAC /*! HMAC(K, text) = H(K XOR opad, H(K XOR ipad, text)) */ template -class HMAC : public MessageAuthenticationCodeTemplate > +class HMAC : public MessageAuthenticationCodeImpl > { public: + enum {DIGESTSIZE=T::DIGESTSIZE, BLOCKSIZE=T::BLOCKSIZE}; + HMAC() {} - HMAC(const byte *key, unsigned int length=HMAC_Base::DEFAULT_KEYLENGTH) + HMAC(const byte *key, unsigned int length=HMAC_Base::DEFAULT_KEYLENGTH) {SetKey(key, length);} + + static std::string StaticAlgorithmName() {return std::string("HMAC(") + T::StaticAlgorithmName() + ")";} + +private: + HashTransformation & AccessHash() {return m_hash;} + byte * AccessIpad() {return m_ipad;} + byte * AccessOpad() {return m_opad;} + byte * AccessInnerHash() {return m_innerHash;} + + FixedSizeSecBlock m_ipad, m_opad; + FixedSizeSecBlock m_innerHash; + T m_hash; }; -template -void HMAC_Base::UncheckedSetKey(const byte *userKey, unsigned int keylength) -{ - AssertValidKeyLength(keylength); - - Restart(); - - if (keylength <= T::BLOCKSIZE) - memcpy(k_ipad, userKey, keylength); - else - { - m_hash.CalculateDigest(k_ipad, userKey, keylength); - keylength = T::DIGESTSIZE; - } - - assert(keylength <= T::BLOCKSIZE); - memset(k_ipad+keylength, 0, T::BLOCKSIZE-keylength); - - for (unsigned int i=0; i -void HMAC_Base::KeyInnerHash() -{ - assert(!m_innerHashKeyed); - m_hash.Update(k_ipad, T::BLOCKSIZE); - m_innerHashKeyed = true; -} - -template -void HMAC_Base::Restart() -{ - if (m_innerHashKeyed) - { - m_hash.Restart(); - m_innerHashKeyed = false; - } -} - -template -void HMAC_Base::Update(const byte *input, unsigned int length) -{ - if (!m_innerHashKeyed) - KeyInnerHash(); - m_hash.Update(input, length); -} - -template -void HMAC_Base::TruncatedFinal(byte *mac, unsigned int size) -{ - ThrowIfInvalidTruncatedSize(size); - - if (!m_innerHashKeyed) - KeyInnerHash(); - m_hash.Final(m_innerHash); - - m_hash.Update(k_opad, T::BLOCKSIZE); - m_hash.Update(m_innerHash, DIGESTSIZE); - m_hash.TruncatedFinal(mac, size); - - m_innerHashKeyed = false; -} - NAMESPACE_END #endif diff --git a/idea.h b/idea.h index 09624caa..b33be628 100644 --- a/idea.h +++ b/idea.h @@ -17,7 +17,7 @@ struct IDEA_Info : public FixedBlockSize<8>, public FixedKeyLength<16>, public F /// IDEA class IDEA : public IDEA_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: unsigned int GetAlignment() const {return 2;} @@ -40,8 +40,8 @@ class IDEA : public IDEA_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef IDEA::Encryption IDEAEncryption; diff --git a/integer.cpp b/integer.cpp index 260f6f0e..bf7508c3 100644 --- a/integer.cpp +++ b/integer.cpp @@ -2,6 +2,9 @@ // contains public domain code contributed by Alister Lee and Leonard Janke #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "integer.h" #include "modarith.h" #include "nbtheory.h" @@ -20,9 +23,6 @@ #pragma message("You do no seem to have the Visual C++ Processor Pack installed, so use of SSE2 intrinsics will be disabled.") #endif -#include "algebra.cpp" -#include "eprecomp.cpp" - NAMESPACE_BEGIN(CryptoPP) bool FunctionAssignIntToInteger(const std::type_info &valueType, void *pInteger, const void *pInt) @@ -58,8 +58,6 @@ void AlignedAllocator::deallocate(void *p, size_type n) #endif delete [] p; } - -template class AlignedAllocator; #endif #define MAKE_DWORD(lowWord, highWord) ((dword(highWord)<; - NAMESPACE_END + +#endif diff --git a/integer.h b/integer.h index 503a74f9..b8284614 100644 --- a/integer.h +++ b/integer.h @@ -24,6 +24,7 @@ NAMESPACE_BEGIN(CryptoPP) #if defined(SSE2_INTRINSICS_AVAILABLE) || defined(_MSC_VER) + template class AlignedAllocator : public AllocatorBase { @@ -37,7 +38,11 @@ NAMESPACE_BEGIN(CryptoPP) return StandardReallocate(*this, p, oldSize, newSize, preserve); } }; +template class CRYPTOPP_DLL AlignedAllocator; typedef SecBlock > SecAlignedWordBlock; + +void CRYPTOPP_DLL DisableSSE2(); + #else typedef SecWordBlock SecAlignedWordBlock; #endif @@ -47,7 +52,7 @@ NAMESPACE_BEGIN(CryptoPP) with absolute value less than (256**sizeof(word)) ** (256**sizeof(int)). \nosubgrouping */ -class Integer : public ASN1Object +class CRYPTOPP_DLL Integer : public ASN1Object { public: //! \name ENUMS, EXCEPTIONS, and TYPEDEFS @@ -355,9 +360,9 @@ public: Integer MultiplicativeInverse() const; //! modular multiplication - friend Integer a_times_b_mod_c(const Integer &x, const Integer& y, const Integer& m); + CRYPTOPP_DLL friend Integer a_times_b_mod_c(const Integer &x, const Integer& y, const Integer& m); //! modular exponentiation - friend Integer a_exp_b_mod_c(const Integer &x, const Integer& e, const Integer& m); + CRYPTOPP_DLL friend Integer a_exp_b_mod_c(const Integer &x, const Integer& e, const Integer& m); //! calculate r and q such that (a == d*q + r) && (0 <= r < abs(d)) static void Divide(Integer &r, Integer &q, const Integer &a, const Integer &d); @@ -378,9 +383,9 @@ public: //! \name INPUT/OUTPUT //@{ //! - friend std::istream& operator>>(std::istream& in, Integer &a); + friend CRYPTOPP_DLL std::istream& operator>>(std::istream& in, Integer &a); //! - friend std::ostream& operator<<(std::ostream& out, const Integer &a); + friend CRYPTOPP_DLL std::ostream& operator<<(std::ostream& out, const Integer &a); //@} private: diff --git a/iterhash.cpp b/iterhash.cpp index 00cc12bc..7e1187f4 100644 --- a/iterhash.cpp +++ b/iterhash.cpp @@ -1,18 +1,14 @@ // iterhash.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "iterhash.h" #include "misc.h" NAMESPACE_BEGIN(CryptoPP) -template -IteratedHashBase::IteratedHashBase(unsigned int blockSize, unsigned int digestSize) - : m_data(blockSize/sizeof(T)), m_digest(digestSize/sizeof(T)) - , m_countHi(0), m_countLo(0) -{ -} - template void IteratedHashBase::Update(const byte *input, unsigned int len) { HashWordType tmp = m_countLo; @@ -111,12 +107,6 @@ template void IteratedHashBase::Restart() Init(); } -#ifdef WORD64_AVAILABLE -template class IteratedHashBase; -template class IteratedHashBase; -#endif - -template class IteratedHashBase; -template class IteratedHashBase; - NAMESPACE_END + +#endif diff --git a/iterhash.h b/iterhash.h index 362379e7..0911feeb 100644 --- a/iterhash.h +++ b/iterhash.h @@ -4,6 +4,7 @@ #include "cryptlib.h" #include "secblock.h" #include "misc.h" +#include "simple.h" NAMESPACE_BEGIN(CryptoPP) @@ -13,8 +14,10 @@ class CRYPTOPP_NO_VTABLE IteratedHashBase : public BASE public: typedef T HashWordType; - IteratedHashBase(unsigned int blockSize, unsigned int digestSize); - unsigned int DigestSize() const {return m_digest.size() * sizeof(T);}; + IteratedHashBase() : m_countHi(0), m_countLo(0) {} + void SetBlockSize(unsigned int blockSize) {m_data.resize(blockSize / sizeof(HashWordType));} + void SetStateSize(unsigned int stateSize) {m_digest.resize(stateSize / sizeof(HashWordType));} + unsigned int BlockSize() const {return m_data.size() * sizeof(T);} unsigned int OptimalBlockSize() const {return BlockSize();} unsigned int OptimalDataAlignment() const {return sizeof(T);} void Update(const byte *input, unsigned int length); @@ -29,7 +32,6 @@ protected: void PadLastBlock(unsigned int lastBlockSize, byte padFirst=0x80); virtual void Init() =0; virtual void HashBlock(const T *input) =0; - virtual unsigned int BlockSize() const =0; SecBlock m_data; // Data buffer SecBlock m_digest; // Message digest @@ -38,14 +40,19 @@ private: T m_countLo, m_countHi; }; +#ifdef WORD64_AVAILABLE +CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase; +CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase; +#endif + +CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase; +CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase; + //! . template class CRYPTOPP_NO_VTABLE IteratedHashBase2 : public IteratedHashBase { public: - IteratedHashBase2(unsigned int blockSize, unsigned int digestSize) - : IteratedHashBase(blockSize, digestSize) {} - typedef B ByteOrderClass; typedef typename IteratedHashBase::HashWordType HashWordType; @@ -58,32 +65,37 @@ public: protected: void HashBlock(const HashWordType *input); - - virtual void vTransform(const HashWordType *data) =0; + virtual void HashEndianCorrectedBlock(const HashWordType *data) =0; }; //! . -template -class CRYPTOPP_NO_VTABLE IteratedHash : public IteratedHashBase2 +template +class CRYPTOPP_NO_VTABLE IteratedHash : public IteratedHashBase2 { public: - enum {BLOCKSIZE = S}; - -private: + enum {BLOCKSIZE = T_BlockSize}; CRYPTOPP_COMPILE_ASSERT((BLOCKSIZE & (BLOCKSIZE - 1)) == 0); // blockSize is a power of 2 protected: - IteratedHash(unsigned int digestSize) : IteratedHashBase2(BLOCKSIZE, digestSize) {} - unsigned int BlockSize() const {return BLOCKSIZE;} + IteratedHash() {SetBlockSize(T_BlockSize);} }; -template -class CRYPTOPP_NO_VTABLE IteratedHashWithStaticTransform : public IteratedHash +template +class CRYPTOPP_NO_VTABLE IteratedHashWithStaticTransform + : public ClonableImpl, T_Transform> > { +public: + enum {DIGESTSIZE = T_DigestSize}; + unsigned int DigestSize() const {return DIGESTSIZE;}; + protected: - IteratedHashWithStaticTransform(unsigned int digestSize) : IteratedHash(digestSize) {} - void vTransform(const T *data) {M::Transform(m_digest, data);} - std::string AlgorithmName() const {return M::StaticAlgorithmName();} + IteratedHashWithStaticTransform() + { + SetStateSize(T_StateSize); + Init(); + } + void HashEndianCorrectedBlock(const T_HashWordType *data) {T_Transform::Transform(m_digest, data);} + void Init() {T_Transform::InitState(m_digest);} }; // ************************************************************* @@ -98,7 +110,7 @@ template void IteratedHashBase2::Trun m_data[m_data.size()-2] = B::ToEnum() ? GetBitCountHi() : GetBitCountLo(); m_data[m_data.size()-1] = B::ToEnum() ? GetBitCountLo() : GetBitCountHi(); - vTransform(m_data); + HashEndianCorrectedBlock(m_data); CorrectEndianess(m_digest, m_digest, DigestSize()); memcpy(hash, m_digest, size); @@ -108,11 +120,11 @@ template void IteratedHashBase2::Trun template void IteratedHashBase2::HashBlock(const HashWordType *input) { if (NativeByteOrderIs(B::ToEnum())) - vTransform(input); + HashEndianCorrectedBlock(input); else { ByteReverse(m_data.begin(), input, BlockSize()); - vTransform(m_data); + HashEndianCorrectedBlock(m_data); } } diff --git a/lubyrack.h b/lubyrack.h index 9c0d55a1..9171a24a 100644 --- a/lubyrack.h +++ b/lubyrack.h @@ -23,7 +23,7 @@ struct LR_Info : public VariableKeyLength<16, 0, 2*(UINT_MAX/2), 2>, public Fixe template class LR : public LR_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate > + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl > { public: // VC60 workaround: have to define these functions within class definition @@ -129,8 +129,8 @@ class LR : public LR_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; NAMESPACE_END diff --git a/luc.cpp b/luc.cpp index 88146134..85bd4623 100644 --- a/luc.cpp +++ b/luc.cpp @@ -7,8 +7,6 @@ #include "sha.h" #include "algparam.h" -#include "oaep.cpp" - NAMESPACE_BEGIN(CryptoPP) void LUC_TestInstantiations() diff --git a/mars.h b/mars.h index 674c7b41..3b3c1815 100644 --- a/mars.h +++ b/mars.h @@ -17,7 +17,7 @@ struct MARS_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 5 /// MARS class MARS : public MARS_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -41,8 +41,8 @@ class MARS : public MARS_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef MARS::Encryption MARSEncryption; diff --git a/md4.cpp b/md4.cpp index 525f0c8f..c67ef066 100644 --- a/md4.cpp +++ b/md4.cpp @@ -20,12 +20,12 @@ NAMESPACE_BEGIN(CryptoPP) -void MD4::Init() +void MD4::InitState(HashWordType *state) { - m_digest[0] = 0x67452301L; - m_digest[1] = 0xefcdab89L; - m_digest[2] = 0x98badcfeL; - m_digest[3] = 0x10325476L; + state[0] = 0x67452301L; + state[1] = 0xefcdab89L; + state[2] = 0x98badcfeL; + state[3] = 0x10325476L; } void MD4::Transform (word32 *digest, const word32 *in) diff --git a/md4.h b/md4.h index 22a7ab8a..b33104ca 100644 --- a/md4.h +++ b/md4.h @@ -8,16 +8,12 @@ NAMESPACE_BEGIN(CryptoPP) //! MD4 /*! \warning MD4 is considered insecure, and should not be used unless you absolutely need compatibility with a broken product. */ -class MD4 : public IteratedHashWithStaticTransform +class MD4 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 16}; - MD4() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char *StaticAlgorithmName() {return "MD4";} - -protected: - void Init(); }; NAMESPACE_END diff --git a/md5.cpp b/md5.cpp index 7bd4f385..cfe81a27 100644 --- a/md5.cpp +++ b/md5.cpp @@ -12,12 +12,12 @@ void MD5_TestInstantiations() MD5 x; } -void MD5::Init() +void MD5::InitState(HashWordType *state) { - m_digest[0] = 0x67452301L; - m_digest[1] = 0xefcdab89L; - m_digest[2] = 0x98badcfeL; - m_digest[3] = 0x10325476L; + state[0] = 0x67452301L; + state[1] = 0xefcdab89L; + state[2] = 0x98badcfeL; + state[3] = 0x10325476L; } void MD5::Transform (word32 *digest, const word32 *in) diff --git a/md5.h b/md5.h index 2e8850f9..f17780ed 100644 --- a/md5.h +++ b/md5.h @@ -7,16 +7,12 @@ NAMESPACE_BEGIN(CryptoPP) //! MD5 /*! 128 Bit Hash */ -class MD5 : public IteratedHashWithStaticTransform +class MD5 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 16}; - MD5() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char * StaticAlgorithmName() {return "MD5";} - -protected: - void Init(); }; NAMESPACE_END diff --git a/md5mac.h b/md5mac.h index 2a599601..92750066 100644 --- a/md5mac.h +++ b/md5mac.h @@ -16,14 +16,15 @@ public: static std::string StaticAlgorithmName() {return "MD5-MAC";} enum {DIGESTSIZE = 16}; - MD5MAC_Base() : IteratedHash(DIGESTSIZE) {} + MD5MAC_Base() {SetStateSize(DIGESTSIZE);} void UncheckedSetKey(const byte *userKey, unsigned int keylength); void TruncatedFinal(byte *mac, unsigned int size); + unsigned int DigestSize() const {return DIGESTSIZE;} protected: static void Transform (word32 *buf, const word32 *in, const word32 *key); - void vTransform(const word32 *data) {Transform(m_digest, data, m_key+4);} + void HashEndianCorrectedBlock(const word32 *data) {Transform(m_digest, data, m_key+4);} void Init(); static const word32 T[12]; @@ -31,7 +32,7 @@ protected: }; //! MD5-MAC -typedef MessageAuthenticationCodeTemplate MD5MAC; +typedef MessageAuthenticationCodeFinal MD5MAC; NAMESPACE_END diff --git a/mdc.h b/mdc.h index ff043602..b587f153 100644 --- a/mdc.h +++ b/mdc.h @@ -22,7 +22,7 @@ struct MDC_Info : public FixedBlockSize, public FixedKeyLength class MDC : public MDC_Info { - class CRYPTOPP_NO_VTABLE Enc : public BlockCipherBaseTemplate > + class CRYPTOPP_NO_VTABLE Enc : public BlockCipherImpl > { typedef typename T::HashWordType HashWordType; @@ -64,7 +64,7 @@ class MDC : public MDC_Info public: //! use BlockCipher interface - typedef BlockCipherTemplate Encryption; + typedef BlockCipherFinal Encryption; }; NAMESPACE_END diff --git a/misc.cpp b/misc.cpp index c193b3f3..9430e445 100644 --- a/misc.cpp +++ b/misc.cpp @@ -1,19 +1,14 @@ // misc.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "misc.h" #include "words.h" NAMESPACE_BEGIN(CryptoPP) -byte OAEP_P_DEFAULT[1]; - -template<> void ByteReverse(word16 *, const word16 *, unsigned int); -template<> void ByteReverse(word32 *, const word32 *, unsigned int); -#ifdef WORD64_AVAILABLE -template<> void ByteReverse(word64 *, const word64 *, unsigned int); -#endif - void xorbuf(byte *buf, const byte *mask, unsigned int count) { if (((unsigned int)buf | (unsigned int)mask | count) % WORD_SIZE == 0) @@ -81,3 +76,5 @@ unsigned long Crop(unsigned long value, unsigned int size) } NAMESPACE_END + +#endif diff --git a/misc.h b/misc.h index 527a0580..c90cf316 100644 --- a/misc.h +++ b/misc.h @@ -1,12 +1,7 @@ #ifndef CRYPTOPP_MISC_H #define CRYPTOPP_MISC_H -#include "config.h" #include "cryptlib.h" -#include -#include // CodeWarrior doesn't have memory.h -#include -#include #ifdef INTEL_INTRINSICS #include @@ -23,13 +18,17 @@ struct CompileAssert }; #define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__) +#if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS) +#define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) +#else #define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) static CompileAssert<(assertion)> CRYPTOPP_ASSERT_JOIN(cryptopp_assert_, instance) +#endif #define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y) #define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y // ************** misc classes *************** -class Empty +class CRYPTOPP_DLL Empty { }; @@ -80,10 +79,10 @@ template inline const _Tp& STDMAX(const _Tp& __a, const _Tp& __b) // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255) // #define GETBYTE(x, y) (((byte *)&(x))[y]) -unsigned int Parity(unsigned long); -unsigned int BytePrecision(unsigned long); -unsigned int BitPrecision(unsigned long); -unsigned long Crop(unsigned long, unsigned int size); +CRYPTOPP_DLL unsigned int Parity(unsigned long); +CRYPTOPP_DLL unsigned int BytePrecision(unsigned long); +CRYPTOPP_DLL unsigned int BitPrecision(unsigned long); +CRYPTOPP_DLL unsigned long Crop(unsigned long, unsigned int size); inline unsigned int BitsToBytes(unsigned int bitCount) { @@ -100,8 +99,8 @@ inline unsigned int BitsToWords(unsigned int bitCount) return ((bitCount+WORD_BITS-1)/(WORD_BITS)); } -void xorbuf(byte *buf, const byte *mask, unsigned int count); -void xorbuf(byte *output, const byte *input, const byte *mask, unsigned int count); +CRYPTOPP_DLL void xorbuf(byte *buf, const byte *mask, unsigned int count); +CRYPTOPP_DLL void xorbuf(byte *output, const byte *input, const byte *mask, unsigned int count); template inline bool IsPowerOf2(T n) diff --git a/modarith.h b/modarith.h index b97b1060..365f4c5e 100644 --- a/modarith.h +++ b/modarith.h @@ -10,8 +10,12 @@ NAMESPACE_BEGIN(CryptoPP) +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup; +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing; +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractEuclideanDomain; + //! . -class ModularArithmetic : public AbstractRing +class CRYPTOPP_DLL ModularArithmetic : public AbstractRing { public: @@ -99,6 +103,9 @@ public: return Element( rng , Integer( (long) 0) , modulus - Integer( (long) 1 ) ) ; } + bool operator==(const ModularArithmetic &rhs) const + {return modulus == rhs.modulus;} + static const RandomizationParameter DefaultRandomizationParameter ; protected: @@ -110,7 +117,7 @@ protected: // const ModularArithmetic::RandomizationParameter ModularArithmetic::DefaultRandomizationParameter = 0 ; //! do modular arithmetics in Montgomery representation for increased speed -class MontgomeryRepresentation : public ModularArithmetic +class CRYPTOPP_DLL MontgomeryRepresentation : public ModularArithmetic { public: MontgomeryRepresentation(const Integer &modulus); // modulus must be odd diff --git a/modes.cpp b/modes.cpp index 09c370ee..0d163cb2 100644 --- a/modes.cpp +++ b/modes.cpp @@ -1,14 +1,18 @@ // modes.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "modes.h" +#ifndef NDEBUG #include "des.h" - -#include "strciphr.cpp" +#endif NAMESPACE_BEGIN(CryptoPP) +#ifndef NDEBUG void Modes_TestInstantiations() { CFB_Mode::Encryption m0; @@ -18,17 +22,7 @@ void Modes_TestInstantiations() ECB_Mode::Encryption m4; CBC_Mode::Encryption m5; } - -// explicit instantiations for Darwin gcc-932.1 -template class CFB_CipherTemplate >; -template class CFB_EncryptionTemplate<>; -template class CFB_DecryptionTemplate<>; -template class AdditiveCipherTemplate<>; -template class CFB_CipherTemplate >; -template class CFB_EncryptionTemplate >; -template class CFB_DecryptionTemplate >; -template class AdditiveCipherTemplate >; -template class AdditiveCipherTemplate >; +#endif void CipherModeBase::SetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms) { @@ -64,8 +58,15 @@ static inline void IncrementCounterByOne(byte *inout, unsigned int s) static inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int s) { - for (int i=s-1, carry=1; i>=0; i--) - carry = !(output[i] = input[i]+carry) && carry; + int i, carry; + for (i=s-1, carry=1; i>=0 && carry; i--) + carry = !(output[i] = input[i]+1); + memcpy(output, input, i+1); +} + +void CTR_ModePolicy::GetNextIV(byte *IV) +{ + IncrementCounterByOne(IV, m_counterArray, BlockSize()); } inline void CTR_ModePolicy::ProcessMultipleBlocks(byte *output, const byte *input, unsigned int n) @@ -248,3 +249,5 @@ void CBC_CTS_Decryption::ProcessLastBlock(byte *outString, const byte *inString, } NAMESPACE_END + +#endif diff --git a/modes.h b/modes.h index 4dd1437a..e6b30e09 100644 --- a/modes.h +++ b/modes.h @@ -28,7 +28,7 @@ struct CipherModeDocumentation : public SymmetricCipherDocumentation { }; -class CRYPTOPP_NO_VTABLE CipherModeBase : public SymmetricCipher +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CipherModeBase : public SymmetricCipher { public: unsigned int MinKeyLength() const {return m_cipher->MinKeyLength();} @@ -66,16 +66,19 @@ template class CRYPTOPP_NO_VTABLE ModePolicyCommonTemplate : public CipherModeBase, public POLICY_INTERFACE { unsigned int GetAlignment() const {return m_cipher->BlockAlignment();} - void CipherSetKey(const NameValuePairs ¶ms, const byte *key, unsigned int length) - { - m_cipher->SetKey(key, length, params); - ResizeBuffers(); - int feedbackSize = params.GetIntValueWithDefault(Name::FeedbackSize(), 0); - SetFeedbackSize(feedbackSize); - } + void CipherSetKey(const NameValuePairs ¶ms, const byte *key, unsigned int length); }; -class CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate +template +void ModePolicyCommonTemplate::CipherSetKey(const NameValuePairs ¶ms, const byte *key, unsigned int length) +{ + m_cipher->SetKey(key, length, params); + ResizeBuffers(); + int feedbackSize = params.GetIntValueWithDefault(Name::FeedbackSize(), 0); + SetFeedbackSize(feedbackSize); +} + +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate { public: IV_Requirement IVRequirement() const {return RANDOM_IV;} @@ -118,25 +121,35 @@ inline void CopyOrZero(void *dest, const void *src, size_t s) memset(dest, 0, s); } -class CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate { +public: + bool IsRandomAccess() const {return false;} + IV_Requirement IVRequirement() const {return STRUCTURED_IV;} + +private: unsigned int GetBytesPerIteration() const {return BlockSize();} unsigned int GetIterationsToBuffer() const {return 1;} void WriteKeystream(byte *keystreamBuffer, unsigned int iterationCount) { assert(iterationCount == 1); m_cipher->ProcessBlock(keystreamBuffer); + memcpy(m_register, keystreamBuffer, BlockSize()); } void CipherResynchronize(byte *keystreamBuffer, const byte *iv) { CopyOrZero(keystreamBuffer, iv, BlockSize()); } - bool IsRandomAccess() const {return false;} - IV_Requirement IVRequirement() const {return STRUCTURED_IV;} }; -class CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate { +public: + bool IsRandomAccess() const {return true;} + IV_Requirement IVRequirement() const {return STRUCTURED_IV;} + void GetNextIV(byte *IV); + +private: unsigned int GetBytesPerIteration() const {return BlockSize();} unsigned int GetIterationsToBuffer() const {return m_cipher->OptimalNumberOfParallelBlocks();} void WriteKeystream(byte *buffer, unsigned int iterationCount) @@ -144,16 +157,14 @@ class CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplateProcessAndXorMultipleBlocks(inString, NULL, outString, numberOfBlocks);} }; -class CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase { public: IV_Requirement IVRequirement() const {return UNPREDICTABLE_RANDOM_IV;} @@ -193,13 +204,13 @@ public: unsigned int MinLastBlockSize() const {return 0;} }; -class CRYPTOPP_NO_VTABLE CBC_Encryption : public CBC_ModeBase +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Encryption : public CBC_ModeBase { public: void ProcessBlocks(byte *outString, const byte *inString, unsigned int numberOfBlocks); }; -class CRYPTOPP_NO_VTABLE CBC_CTS_Encryption : public CBC_Encryption +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Encryption : public CBC_Encryption { public: void SetStolenIV(byte *iv) {m_stolenIV = iv;} @@ -216,7 +227,7 @@ protected: byte *m_stolenIV; }; -class CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase { public: void ProcessBlocks(byte *outString, const byte *inString, unsigned int numberOfBlocks); @@ -230,7 +241,7 @@ protected: SecByteBlock m_temp; }; -class CRYPTOPP_NO_VTABLE CBC_CTS_Decryption : public CBC_Decryption +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Decryption : public CBC_Decryption { public: unsigned int MinLastBlockSize() const {return BlockSize()+1;} @@ -264,24 +275,32 @@ template class CipherModeFinalTemplate_ExternalCipher : public BASE { public: - CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher) - { - ThrowIfResynchronizable(); - m_cipher = &cipher; - ResizeBuffers(); - } + CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher); - CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize = 0) - { - ThrowIfInvalidIV(iv); - m_cipher = &cipher; - ResizeBuffers(); - SetFeedbackSize(feedbackSize); - if (IsResynchronizable()) - Resynchronize(iv); - } + CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize = 0); }; +template CipherModeFinalTemplate_ExternalCipher::CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher) +{ + ThrowIfResynchronizable(); + m_cipher = &cipher; + ResizeBuffers(); +} + +template CipherModeFinalTemplate_ExternalCipher::CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize) +{ + ThrowIfInvalidIV(iv); + m_cipher = &cipher; + ResizeBuffers(); + SetFeedbackSize(feedbackSize); + if (IsResynchronizable()) + Resynchronize(iv); +} + +CRYPTOPP_DLL_TEMPLATE_CLASS CFB_CipherTemplate >; +CRYPTOPP_DLL_TEMPLATE_CLASS CFB_EncryptionTemplate >; +CRYPTOPP_DLL_TEMPLATE_CLASS CFB_DecryptionTemplate >; + //! CFB mode template struct CFB_Mode : public CipherModeDocumentation @@ -297,6 +316,8 @@ struct CFB_Mode_ExternalCipher : public CipherModeDocumentation typedef CipherModeFinalTemplate_ExternalCipher > > > Decryption; }; +CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate >; + //! OFB mode template struct OFB_Mode : public CipherModeDocumentation @@ -312,6 +333,8 @@ struct OFB_Mode_ExternalCipher : public CipherModeDocumentation typedef Encryption Decryption; }; +CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate >; + //! CTR mode template struct CTR_Mode : public CipherModeDocumentation @@ -335,6 +358,8 @@ struct ECB_Mode : public CipherModeDocumentation typedef CipherModeFinalTemplate_CipherHolder Decryption; }; +CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher; + //! ECB mode, external cipher struct ECB_Mode_ExternalCipher : public CipherModeDocumentation { @@ -350,6 +375,9 @@ struct CBC_Mode : public CipherModeDocumentation typedef CipherModeFinalTemplate_CipherHolder Decryption; }; +CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher; +CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher; + //! CBC mode, external cipher struct CBC_Mode_ExternalCipher : public CipherModeDocumentation { @@ -365,6 +393,9 @@ struct CBC_CTS_Mode : public CipherModeDocumentation typedef CipherModeFinalTemplate_CipherHolder Decryption; }; +CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher; +CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher; + //! CBC mode with ciphertext stealing, external cipher struct CBC_CTS_Mode_ExternalCipher : public CipherModeDocumentation { diff --git a/modexppc.cpp b/modexppc.cpp index 454854de..bea2931a 100644 --- a/modexppc.cpp +++ b/modexppc.cpp @@ -1,16 +1,14 @@ // modexppc.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "modexppc.h" #include "asn.h" -#include "algebra.cpp" -#include "eprecomp.cpp" - NAMESPACE_BEGIN(CryptoPP) -template class DL_FixedBasePrecomputationImpl; - /* ModExpPrecomputation& ModExpPrecomputation::operator=(const ModExpPrecomputation &rhs) { @@ -78,3 +76,5 @@ Integer ModExpPrecomputation::CascadeExponentiate(const Integer &exponent, const */ NAMESPACE_END + +#endif diff --git a/modexppc.h b/modexppc.h index 05cdaa6e..fbe70127 100644 --- a/modexppc.h +++ b/modexppc.h @@ -8,6 +8,8 @@ NAMESPACE_BEGIN(CryptoPP) +CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl; + class ModExpPrecomputation : public DL_GroupPrecomputation { public: diff --git a/mqueue.cpp b/mqueue.cpp index 2bac976c..8e0d6e92 100644 --- a/mqueue.cpp +++ b/mqueue.cpp @@ -1,6 +1,9 @@ // mqueue.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "mqueue.h" NAMESPACE_BEGIN(CryptoPP) @@ -180,3 +183,5 @@ bool EqualityComparisonFilter::HandleMismatchDetected(bool blocking) } NAMESPACE_END + +#endif diff --git a/mqueue.h b/mqueue.h index edc701a7..6d7d04b8 100644 --- a/mqueue.h +++ b/mqueue.h @@ -8,7 +8,7 @@ NAMESPACE_BEGIN(CryptoPP) //! Message Queue -class MessageQueue : public AutoSignaling +class CRYPTOPP_DLL MessageQueue : public AutoSignaling { public: MessageQueue(unsigned int nodeSize=256); @@ -62,7 +62,7 @@ private: //! A filter that checks messages on two channels for equality -class EqualityComparisonFilter : public Unflushable > +class CRYPTOPP_DLL EqualityComparisonFilter : public Unflushable > { public: struct MismatchDetected : public Exception {MismatchDetected() : Exception(DATA_INTEGRITY_CHECK_FAILED, "EqualityComparisonFilter: did not receive the same data on two channels") {}}; diff --git a/nbtheory.cpp b/nbtheory.cpp index 8689cea7..d691e43c 100644 --- a/nbtheory.cpp +++ b/nbtheory.cpp @@ -1,6 +1,9 @@ // nbtheory.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "nbtheory.h" #include "modarith.h" #include "algparam.h" @@ -1125,3 +1128,5 @@ void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, u } NAMESPACE_END + +#endif diff --git a/nbtheory.h b/nbtheory.h index 685dc41a..3ef517dc 100644 --- a/nbtheory.h +++ b/nbtheory.h @@ -15,39 +15,39 @@ extern unsigned int primeTableSize; extern word primeTable[]; // build up the table to maxPrimeTableSize -void BuildPrimeTable(); +CRYPTOPP_DLL void BuildPrimeTable(); // ************ primality testing **************** // generate a provable prime -Integer MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits); -Integer MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int bits); +CRYPTOPP_DLL Integer MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits); +CRYPTOPP_DLL Integer MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int bits); -bool IsSmallPrime(const Integer &p); +CRYPTOPP_DLL bool IsSmallPrime(const Integer &p); // returns true if p is divisible by some prime less than bound // bound not be greater than the largest entry in the prime table -bool TrialDivision(const Integer &p, unsigned bound); +CRYPTOPP_DLL bool TrialDivision(const Integer &p, unsigned bound); // returns true if p is NOT divisible by small primes -bool SmallDivisorsTest(const Integer &p); +CRYPTOPP_DLL bool SmallDivisorsTest(const Integer &p); // These is no reason to use these two, use the ones below instead -bool IsFermatProbablePrime(const Integer &n, const Integer &b); -bool IsLucasProbablePrime(const Integer &n); +CRYPTOPP_DLL bool IsFermatProbablePrime(const Integer &n, const Integer &b); +CRYPTOPP_DLL bool IsLucasProbablePrime(const Integer &n); -bool IsStrongProbablePrime(const Integer &n, const Integer &b); -bool IsStrongLucasProbablePrime(const Integer &n); +CRYPTOPP_DLL bool IsStrongProbablePrime(const Integer &n, const Integer &b); +CRYPTOPP_DLL bool IsStrongLucasProbablePrime(const Integer &n); // Rabin-Miller primality test, i.e. repeating the strong probable prime test // for several rounds with random bases -bool RabinMillerTest(RandomNumberGenerator &rng, const Integer &w, unsigned int rounds); +CRYPTOPP_DLL bool RabinMillerTest(RandomNumberGenerator &rng, const Integer &w, unsigned int rounds); // primality test, used to generate primes -bool IsPrime(const Integer &p); +CRYPTOPP_DLL bool IsPrime(const Integer &p); // more reliable than IsPrime(), used to verify primes generated by others -bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level = 1); +CRYPTOPP_DLL bool VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level = 1); class PrimeSelector { @@ -58,11 +58,11 @@ public: // use a fast sieve to find the first probable prime in {x | p<=x<=max and x%mod==equiv} // returns true iff successful, value of p is undefined if no such prime exists -bool FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector); +CRYPTOPP_DLL bool FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector); -unsigned int PrimeSearchInterval(const Integer &max); +CRYPTOPP_DLL unsigned int PrimeSearchInterval(const Integer &max); -AlgorithmParameters, Integer>, Integer> +CRYPTOPP_DLL AlgorithmParameters, Integer>, Integer> MakeParametersForTwoPrimesOfEqualSize(unsigned int productBitLength); // ********** other number theoretic functions ************ @@ -77,44 +77,44 @@ inline Integer EuclideanMultiplicativeInverse(const Integer &a, const Integer &b {return a.InverseMod(b);} // use Chinese Remainder Theorem to calculate x given x mod p and x mod q -Integer CRT(const Integer &xp, const Integer &p, const Integer &xq, const Integer &q); +CRYPTOPP_DLL Integer CRT(const Integer &xp, const Integer &p, const Integer &xq, const Integer &q); // use this one if u = inverse of p mod q has been precalculated -Integer CRT(const Integer &xp, const Integer &p, const Integer &xq, const Integer &q, const Integer &u); +CRYPTOPP_DLL Integer CRT(const Integer &xp, const Integer &p, const Integer &xq, const Integer &q, const Integer &u); // if b is prime, then Jacobi(a, b) returns 0 if a%b==0, 1 if a is quadratic residue mod b, -1 otherwise // check a number theory book for what Jacobi symbol means when b is not prime -int Jacobi(const Integer &a, const Integer &b); +CRYPTOPP_DLL int Jacobi(const Integer &a, const Integer &b); // calculates the Lucas function V_e(p, 1) mod n -Integer Lucas(const Integer &e, const Integer &p, const Integer &n); +CRYPTOPP_DLL Integer Lucas(const Integer &e, const Integer &p, const Integer &n); // calculates x such that m==Lucas(e, x, p*q), p q primes -Integer InverseLucas(const Integer &e, const Integer &m, const Integer &p, const Integer &q); +CRYPTOPP_DLL Integer InverseLucas(const Integer &e, const Integer &m, const Integer &p, const Integer &q); // use this one if u=inverse of p mod q has been precalculated -Integer InverseLucas(const Integer &e, const Integer &m, const Integer &p, const Integer &q, const Integer &u); +CRYPTOPP_DLL Integer InverseLucas(const Integer &e, const Integer &m, const Integer &p, const Integer &q, const Integer &u); inline Integer ModularExponentiation(const Integer &a, const Integer &e, const Integer &m) {return a_exp_b_mod_c(a, e, m);} // returns x such that x*x%p == a, p prime -Integer ModularSquareRoot(const Integer &a, const Integer &p); +CRYPTOPP_DLL Integer ModularSquareRoot(const Integer &a, const Integer &p); // returns x such that a==ModularExponentiation(x, e, p*q), p q primes, // and e relatively prime to (p-1)*(q-1) -Integer ModularRoot(const Integer &a, const Integer &e, const Integer &p, const Integer &q); +CRYPTOPP_DLL Integer ModularRoot(const Integer &a, const Integer &e, const Integer &p, const Integer &q); // use this one if dp=d%(p-1), dq=d%(q-1), (d is inverse of e mod (p-1)*(q-1)) // and u=inverse of p mod q have been precalculated -Integer ModularRoot(const Integer &a, const Integer &dp, const Integer &dq, const Integer &p, const Integer &q, const Integer &u); +CRYPTOPP_DLL Integer ModularRoot(const Integer &a, const Integer &dp, const Integer &dq, const Integer &p, const Integer &q, const Integer &u); // find r1 and r2 such that ax^2 + bx + c == 0 (mod p) for x in {r1, r2}, p prime // returns true if solutions exist -bool SolveModularQuadraticEquation(Integer &r1, Integer &r2, const Integer &a, const Integer &b, const Integer &c, const Integer &p); +CRYPTOPP_DLL bool SolveModularQuadraticEquation(Integer &r1, Integer &r2, const Integer &a, const Integer &b, const Integer &c, const Integer &p); // returns log base 2 of estimated number of operations to calculate discrete log or factor a number -unsigned int DiscreteLogWorkFactor(unsigned int bitlength); -unsigned int FactoringWorkFactor(unsigned int bitlength); +CRYPTOPP_DLL unsigned int DiscreteLogWorkFactor(unsigned int bitlength); +CRYPTOPP_DLL unsigned int FactoringWorkFactor(unsigned int bitlength); // ******************************************************** //! generator of prime numbers of special forms -class PrimeAndGenerator +class CRYPTOPP_DLL PrimeAndGenerator { public: PrimeAndGenerator() {} diff --git a/oaep.h b/oaep.h index c242698a..018f6882 100644 --- a/oaep.h +++ b/oaep.h @@ -2,6 +2,7 @@ #define CRYPTOPP_OAEP_H #include "pubkey.h" +#include "sha.h" NAMESPACE_BEGIN(CryptoPP) @@ -20,6 +21,8 @@ public: DecodingResult Unpad(const byte *padded, unsigned int paddedLength, byte *raw) const; }; +CRYPTOPP_DLL_TEMPLATE_CLASS OAEP; + NAMESPACE_END #endif diff --git a/osrng.cpp b/osrng.cpp index 57f92e77..b1a03ca3 100644 --- a/osrng.cpp +++ b/osrng.cpp @@ -3,6 +3,9 @@ // Thanks to Leonard Janke for the suggestion for AutoSeededRandomPool. #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "osrng.h" #ifdef OS_RNG_AVAILABLE @@ -170,3 +173,5 @@ void AutoSeededRandomPool::Reseed(bool blocking, unsigned int seedSize) NAMESPACE_END #endif + +#endif diff --git a/osrng.h b/osrng.h index 902b2eee..655e4edf 100644 --- a/osrng.h +++ b/osrng.h @@ -7,11 +7,12 @@ #include "randpool.h" #include "rng.h" +#include "des.h" NAMESPACE_BEGIN(CryptoPP) //! Exception class for Operating-System Random Number Generator. -class OS_RNG_Err : public Exception +class CRYPTOPP_DLL OS_RNG_Err : public Exception { public: OS_RNG_Err(const std::string &operation); @@ -20,7 +21,7 @@ public: #ifdef NONBLOCKING_RNG_AVAILABLE #ifdef CRYPTOPP_WIN32_AVAILABLE -class MicrosoftCryptoProvider +class CRYPTOPP_DLL MicrosoftCryptoProvider { public: MicrosoftCryptoProvider(); @@ -37,7 +38,7 @@ private: #endif //! encapsulate CryptoAPI's CryptGenRandom or /dev/urandom -class NonblockingRng : public RandomNumberGenerator +class CRYPTOPP_DLL NonblockingRng : public RandomNumberGenerator { public: NonblockingRng(); @@ -60,7 +61,7 @@ protected: #ifdef BLOCKING_RNG_AVAILABLE //! encapsulate /dev/random -class BlockingRng : public RandomNumberGenerator +class CRYPTOPP_DLL BlockingRng : public RandomNumberGenerator { public: BlockingRng(); @@ -74,11 +75,11 @@ protected: #endif -void OS_GenerateRandomBlock(bool blocking, byte *output, unsigned int size); +CRYPTOPP_DLL void OS_GenerateRandomBlock(bool blocking, byte *output, unsigned int size); //! Automaticly Seeded Randomness Pool /*! This class seeds itself using an operating system provided RNG. */ -class AutoSeededRandomPool : public RandomPool +class CRYPTOPP_DLL AutoSeededRandomPool : public RandomPool { public: //! blocking will be ignored if the prefered RNG isn't available @@ -89,7 +90,7 @@ public: //! RNG from ANSI X9.17 Appendix C, seeded using an OS provided RNG template -class AutoSeededX917RNG : public RandomNumberGenerator +class AutoSeededX917RNG : public RandomNumberGenerator, public NotCopyable { public: //! blocking will be ignored if the prefered RNG isn't available @@ -108,6 +109,8 @@ private: unsigned int m_counter; }; +CRYPTOPP_DLL_TEMPLATE_CLASS AutoSeededX917RNG; + template void AutoSeededX917RNG::Reseed(const byte *key, unsigned int keylength, const byte *seed, unsigned long timeVector) { diff --git a/panama.cpp b/panama.cpp index e121a750..7e39e06e 100644 --- a/panama.cpp +++ b/panama.cpp @@ -101,7 +101,7 @@ void PanamaHash::TruncatedFinal(byte *hash, unsigned int size) PadLastBlock(BLOCKSIZE, 0x01); - vTransform(m_data); + HashEndianCorrectedBlock(m_data); Iterate(32); // pull diff --git a/panama.h b/panama.h index d18ba495..e1f73f59 100644 --- a/panama.h +++ b/panama.h @@ -30,13 +30,13 @@ class PanamaHash : protected Panama, public IteratedHash(0) {Panama::Reset();} + PanamaHash() {Panama::Reset();} unsigned int DigestSize() const {return DIGESTSIZE;} void TruncatedFinal(byte *hash, unsigned int size); protected: void Init() {Panama::Reset();} - void vTransform(const word32 *data) {Iterate(1, data);} // push + void HashEndianCorrectedBlock(const word32 *data) {Iterate(1, data);} // push unsigned int HashMultipleBlocks(const word32 *input, unsigned int length); }; @@ -65,7 +65,7 @@ protected: /// Panama MAC template -class PanamaMAC : public MessageAuthenticationCodeTemplate > +class PanamaMAC : public MessageAuthenticationCodeImpl > { public: PanamaMAC() {} @@ -96,7 +96,7 @@ protected: template struct PanamaCipher : public PanamaCipherInfo, public SymmetricCipherDocumentation { - typedef SymmetricCipherFinalTemplate, AdditiveCipherTemplate<> > > Encryption; + typedef SymmetricCipherFinal, AdditiveCipherTemplate<> > > Encryption; typedef Encryption Decryption; }; diff --git a/pkcspad.cpp b/pkcspad.cpp index e04ac9dd..8835721f 100644 --- a/pkcspad.cpp +++ b/pkcspad.cpp @@ -1,14 +1,12 @@ // pkcspad.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + #include "pkcspad.h" #include NAMESPACE_BEGIN(CryptoPP) -template<> const byte PKCS_DigestDecoration::decoration[] = {0x30,0x21,0x30,0x09,0x06,0x05,0x2B,0x0E,0x03,0x02,0x1A,0x05,0x00,0x04,0x14}; -template<> const unsigned int PKCS_DigestDecoration::length = sizeof(PKCS_DigestDecoration::decoration); - template<> const byte PKCS_DigestDecoration::decoration[] = {0x30,0x20,0x30,0x0c,0x06,0x08,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x02,0x05,0x00,0x04,0x10}; template<> const unsigned int PKCS_DigestDecoration::length = sizeof(PKCS_DigestDecoration::decoration); @@ -91,6 +89,8 @@ DecodingResult PKCS_EncryptionPaddingScheme::Unpad(const byte *pkcsBlock, unsign // ******************************************************** +#ifndef CRYPTOPP_IMPORTS + void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(RandomNumberGenerator &rng, const byte *recoverableMessage, unsigned int recoverableMessageLength, HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty, @@ -123,4 +123,6 @@ void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(Rando hash.Final(pDigest); } +#endif + NAMESPACE_END diff --git a/pkcspad.h b/pkcspad.h index 2e14a5e0..1ca9ada0 100644 --- a/pkcspad.h +++ b/pkcspad.h @@ -4,6 +4,10 @@ #include "cryptlib.h" #include "pubkey.h" +#ifdef CRYPTOPP_IS_DLL +#include "sha.h" +#endif + NAMESPACE_BEGIN(CryptoPP) //! EME-PKCS1-v1_5 @@ -17,14 +21,15 @@ public: DecodingResult Unpad(const byte *padded, unsigned int paddedLength, byte *raw) const; }; -template struct PKCS_DigestDecoration +template class PKCS_DigestDecoration { +public: static const byte decoration[]; static const unsigned int length; }; //! EMSA-PKCS1-v1_5 -class PKCS1v15_SignatureMessageEncodingMethod : public PK_DeterministicSignatureMessageEncodingMethod +class CRYPTOPP_DLL PKCS1v15_SignatureMessageEncodingMethod : public PK_DeterministicSignatureMessageEncodingMethod { public: static const char * StaticAlgorithmName() {return "EMSA-PKCS1-v1_5";} @@ -46,7 +51,7 @@ public: }; }; -//! PKCS #1 version 1.5, for use with RSAES and RSASS +//! PKCS #1 version 1.5, for use with RSAES and RSASSA /*! The following hash functions are supported for signature: SHA, MD2, MD5, RIPEMD160, SHA256, SHA384, SHA512. */ struct PKCS1v15 : public SignatureStandard, public EncryptionStandard { @@ -54,6 +59,10 @@ struct PKCS1v15 : public SignatureStandard, public EncryptionStandard typedef PKCS1v15_SignatureMessageEncodingMethod SignatureMessageEncodingMethod; }; +#ifdef CRYPTOPP_IS_DLL +CRYPTOPP_DLL_TEMPLATE_CLASS PKCS_DigestDecoration; +#endif + // PKCS_DecoratedHashModule can be instantiated with the following // classes as specified in PKCS#1 v2.0 and P1363a class SHA; diff --git a/pubkey.cpp b/pubkey.cpp index 00025899..502cbb6c 100644 --- a/pubkey.cpp +++ b/pubkey.cpp @@ -1,6 +1,9 @@ // pubkey.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "pubkey.h" NAMESPACE_BEGIN(CryptoPP) @@ -120,3 +123,5 @@ void TF_EncryptorBase::Encrypt(RandomNumberGenerator &rng, const byte *plainText } NAMESPACE_END + +#endif diff --git a/pubkey.h b/pubkey.h index 65619c1e..9184540a 100644 --- a/pubkey.h +++ b/pubkey.h @@ -44,13 +44,8 @@ NAMESPACE_BEGIN(CryptoPP) -Integer NR_EncodeDigest(unsigned int modulusBits, const byte *digest, unsigned int digestLen); -Integer DSA_EncodeDigest(unsigned int modulusBits, const byte *digest, unsigned int digestLen); - -// ******************************************************** - //! . -class CRYPTOPP_NO_VTABLE TrapdoorFunctionBounds +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TrapdoorFunctionBounds { public: virtual ~TrapdoorFunctionBounds() {} @@ -62,7 +57,7 @@ public: }; //! . -class CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunction : public TrapdoorFunctionBounds +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunction : public TrapdoorFunctionBounds { public: virtual Integer ApplyRandomizedFunction(RandomNumberGenerator &rng, const Integer &x) const =0; @@ -70,7 +65,7 @@ public: }; //! . -class CRYPTOPP_NO_VTABLE TrapdoorFunction : public RandomizedTrapdoorFunction +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TrapdoorFunction : public RandomizedTrapdoorFunction { public: Integer ApplyRandomizedFunction(RandomNumberGenerator &rng, const Integer &x) const @@ -81,7 +76,7 @@ public: }; //! . -class CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunctionInverse +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunctionInverse { public: virtual ~RandomizedTrapdoorFunctionInverse() {} @@ -91,7 +86,7 @@ public: }; //! . -class CRYPTOPP_NO_VTABLE TrapdoorFunctionInverse : public RandomizedTrapdoorFunctionInverse +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TrapdoorFunctionInverse : public RandomizedTrapdoorFunctionInverse { public: virtual ~TrapdoorFunctionInverse() {} @@ -151,14 +146,14 @@ protected: }; //! . -class CRYPTOPP_NO_VTABLE TF_DecryptorBase : public TF_CryptoSystemBase > +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_DecryptorBase : public TF_CryptoSystemBase > { public: DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *cipherText, byte *plainText) const; }; //! . -class CRYPTOPP_NO_VTABLE TF_EncryptorBase : public TF_CryptoSystemBase > +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_EncryptorBase : public TF_CryptoSystemBase > { public: void Encrypt(RandomNumberGenerator &rng, const byte *plainText, unsigned int plainTextLength, byte *cipherText) const; @@ -232,7 +227,7 @@ public: }; }; -class CRYPTOPP_NO_VTABLE PK_DeterministicSignatureMessageEncodingMethod : public PK_SignatureMessageEncodingMethod +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_DeterministicSignatureMessageEncodingMethod : public PK_SignatureMessageEncodingMethod { public: bool VerifyMessageRepresentative( @@ -240,7 +235,7 @@ public: byte *representative, unsigned int representativeBitLength) const; }; -class CRYPTOPP_NO_VTABLE PK_RecoverableSignatureMessageEncodingMethod : public PK_SignatureMessageEncodingMethod +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_RecoverableSignatureMessageEncodingMethod : public PK_SignatureMessageEncodingMethod { public: bool VerifyMessageRepresentative( @@ -248,7 +243,7 @@ public: byte *representative, unsigned int representativeBitLength) const; }; -class DL_SignatureMessageEncodingMethod_DSA : public PK_DeterministicSignatureMessageEncodingMethod +class CRYPTOPP_DLL DL_SignatureMessageEncodingMethod_DSA : public PK_DeterministicSignatureMessageEncodingMethod { public: void ComputeMessageRepresentative(RandomNumberGenerator &rng, @@ -257,7 +252,7 @@ public: byte *representative, unsigned int representativeBitLength) const; }; -class DL_SignatureMessageEncodingMethod_NR : public PK_DeterministicSignatureMessageEncodingMethod +class CRYPTOPP_DLL DL_SignatureMessageEncodingMethod_NR : public PK_DeterministicSignatureMessageEncodingMethod { public: void ComputeMessageRepresentative(RandomNumberGenerator &rng, @@ -266,7 +261,7 @@ public: byte *representative, unsigned int representativeBitLength) const; }; -class CRYPTOPP_NO_VTABLE PK_MessageAccumulatorBase : public PK_MessageAccumulator +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulatorBase : public PK_MessageAccumulator { public: PK_MessageAccumulatorBase() : m_empty(true) {} @@ -318,7 +313,7 @@ protected: }; //! . -class CRYPTOPP_NO_VTABLE TF_SignerBase : public TF_SignatureSchemeBase > +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_SignerBase : public TF_SignatureSchemeBase > { public: void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, unsigned int recoverableMessageLength) const; @@ -326,7 +321,7 @@ public: }; //! . -class CRYPTOPP_NO_VTABLE TF_VerifierBase : public TF_SignatureSchemeBase > +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_VerifierBase : public TF_SignatureSchemeBase > { public: void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, unsigned int signatureLength) const; @@ -487,7 +482,7 @@ public: virtual void GenerateAndMask(HashTransformation &hash, byte *output, unsigned int outputLength, const byte *input, unsigned int inputLength, bool mask = true) const =0; }; -void P1363_MGF1KDF2_Common(HashTransformation &hash, byte *output, unsigned int outputLength, const byte *input, unsigned int inputLength, bool mask, unsigned int counterStart); +CRYPTOPP_DLL void P1363_MGF1KDF2_Common(HashTransformation &hash, byte *output, unsigned int outputLength, const byte *input, unsigned int inputLength, bool mask, unsigned int counterStart); //! . class P1363_MGF1 : public MaskGeneratingFunction @@ -625,7 +620,7 @@ private: }; //! . -template , class BASE = DL_GroupParameters > +template , class BASE = DL_GroupParameters > class DL_GroupParametersImpl : public BASE { public: @@ -637,6 +632,9 @@ public: const DL_FixedBasePrecomputation & GetBasePrecomputation() const {return m_gpc;} DL_FixedBasePrecomputation & AccessBasePrecomputation() {return m_gpc;} + bool operator==(const DL_GroupParametersImpl &rhs) const + {return m_groupPrecomputation.GetCurve() == rhs.m_groupPrecomputation.GetCurve() && m_gpc.GetBase(m_groupPrecomputation) == rhs.m_gpc.GetBase(rhs.m_groupPrecomputation);} + protected: GROUP_PRECOMP m_groupPrecomputation; BASE_PRECOMP m_gpc; @@ -916,7 +914,6 @@ template class CRYPTOPP_NO_VTABLE DL_ElgamalLikeSignatureAlgorithm { public: -// virtual Integer EncodeDigest(unsigned int modulusBits, const byte *digest, unsigned int digestLength) const =0; virtual void Sign(const DL_GroupParameters ¶ms, const Integer &privateKey, const Integer &k, const Integer &e, Integer &r, Integer &s) const =0; virtual bool Verify(const DL_GroupParameters ¶ms, const DL_PublicKey &publicKey, const Integer &e, const Integer &r, const Integer &s) const =0; virtual Integer RecoverPresignature(const DL_GroupParameters ¶ms, const DL_PublicKey &publicKey, const Integer &r, const Integer &s) const diff --git a/queue.cpp b/queue.cpp index d700cf0e..0b430bc7 100644 --- a/queue.cpp +++ b/queue.cpp @@ -1,6 +1,9 @@ // queue.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "queue.h" #include "filters.h" @@ -548,3 +551,5 @@ unsigned int ByteQueue::Walker::CopyRangeTo2(BufferedTransformation &target, uns } NAMESPACE_END + +#endif diff --git a/queue.h b/queue.h index f17efc5b..de913105 100644 --- a/queue.h +++ b/queue.h @@ -13,7 +13,7 @@ NAMESPACE_BEGIN(CryptoPP) class ByteQueueNode; //! Byte Queue -class ByteQueue : public Bufferless +class CRYPTOPP_DLL ByteQueue : public Bufferless { public: ByteQueue(unsigned int m_nodeSize=0); @@ -108,7 +108,7 @@ private: }; //! use this to make sure LazyPut is finalized in event of exception -class LazyPutter +class CRYPTOPP_DLL LazyPutter { public: LazyPutter(ByteQueue &bq, const byte *inString, unsigned int size) diff --git a/rabin.cpp b/rabin.cpp index 7f850560..2204ab5e 100644 --- a/rabin.cpp +++ b/rabin.cpp @@ -7,8 +7,6 @@ #include "sha.h" #include "modarith.h" -#include "oaep.cpp" - NAMESPACE_BEGIN(CryptoPP) void RabinFunction::BERDecode(BufferedTransformation &bt) diff --git a/randpool.cpp b/randpool.cpp index 9fa0b4be..d28f7a9a 100644 --- a/randpool.cpp +++ b/randpool.cpp @@ -2,6 +2,9 @@ // The algorithm in this module comes from PGP's randpool.c #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "randpool.h" #include "mdc.h" #include "sha.h" @@ -98,3 +101,5 @@ void RandomPool::GenerateBlock(byte *outString, unsigned int size) } NAMESPACE_END + +#endif diff --git a/randpool.h b/randpool.h index 6bbe32f7..4a68f2cd 100644 --- a/randpool.h +++ b/randpool.h @@ -10,7 +10,7 @@ NAMESPACE_BEGIN(CryptoPP) /*! This class can be used to generate pseudorandom bytes after seeding the pool with the Put() methods */ -class RandomPool : public RandomNumberGenerator, +class CRYPTOPP_DLL RandomPool : public RandomNumberGenerator, public Bufferless { public: diff --git a/rc2.h b/rc2.h index 963f17cc..20b5ac1b 100644 --- a/rc2.h +++ b/rc2.h @@ -18,7 +18,7 @@ struct RC2_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 1, 128> /// RC2 class RC2 : public RC2_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *key, unsigned int length, unsigned int effectiveKeyLength); @@ -49,7 +49,7 @@ class RC2 : public RC2_Info, public BlockCipherDocumentation }; public: - class Encryption : public BlockCipherTemplate + class Encryption : public BlockCipherFinal { public: Encryption() {} @@ -57,7 +57,7 @@ public: {SetKeyWithEffectiveKeyLength(key, keyLen, effectiveLen);} }; - class Decryption : public BlockCipherTemplate + class Decryption : public BlockCipherFinal { public: Decryption() {} diff --git a/rc5.h b/rc5.h index c28c629a..d594dc70 100644 --- a/rc5.h +++ b/rc5.h @@ -18,7 +18,7 @@ struct RC5_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 0, 255> /// RC5 class RC5 : public RC5_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length, unsigned int rounds); @@ -41,8 +41,8 @@ class RC5 : public RC5_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef RC5::Encryption RC5Encryption; diff --git a/rc6.h b/rc6.h index 9fc14f19..3037765d 100644 --- a/rc6.h +++ b/rc6.h @@ -18,7 +18,7 @@ struct RC6_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 0, 255 /// RC6 class RC6 : public RC6_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length, unsigned int rounds); @@ -41,8 +41,8 @@ class RC6 : public RC6_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef RC6::Encryption RC6Encryption; diff --git a/rdtables.cpp b/rdtables.cpp index 87ae597d..97d43068 100644 --- a/rdtables.cpp +++ b/rdtables.cpp @@ -1,6 +1,9 @@ // Rijndael tables #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "rijndael.h" // VC60 workaround: gives a C4786 warning without this function @@ -702,3 +705,5 @@ const word32 Rijndael::Base::rcon[] = { }; NAMESPACE_END + +#endif diff --git a/resource.h b/resource.h new file mode 100644 index 00000000..861e22ba --- /dev/null +++ b/resource.h @@ -0,0 +1,15 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by cryptopp.rc +// + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/rijndael.cpp b/rijndael.cpp index 857e6bfe..2843bec2 100644 --- a/rijndael.cpp +++ b/rijndael.cpp @@ -29,6 +29,9 @@ */ #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "rijndael.h" #include "misc.h" @@ -373,3 +376,5 @@ void Rijndael::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock } NAMESPACE_END + +#endif diff --git a/rijndael.h b/rijndael.h index a1540481..efa788a3 100644 --- a/rijndael.h +++ b/rijndael.h @@ -11,13 +11,13 @@ NAMESPACE_BEGIN(CryptoPP) struct Rijndael_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 8> { - static const char *StaticAlgorithmName() {return "Rijndael";} + CRYPTOPP_DLL static const char * StaticAlgorithmName() {return "Rijndael";} }; /// Rijndael -class Rijndael : public Rijndael_Info, public BlockCipherDocumentation +class CRYPTOPP_DLL Rijndael : public Rijndael_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -41,21 +41,21 @@ class Rijndael : public Rijndael_Info, public BlockCipherDocumentation SecBlock m_key; }; - class CRYPTOPP_NO_VTABLE Enc : public Base + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Enc : public Base { public: void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; }; - class CRYPTOPP_NO_VTABLE Dec : public Base + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Dec : public Base { public: void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Rijndael::Encryption RijndaelEncryption; diff --git a/ripemd.cpp b/ripemd.cpp index 4bdcfc54..3476aa8b 100644 --- a/ripemd.cpp +++ b/ripemd.cpp @@ -34,13 +34,13 @@ NAMESPACE_BEGIN(CryptoPP) a = rotlFixed((word32)a, s) + e;\ c = rotlFixed((word32)c, 10U) -void RIPEMD160::Init() +void RIPEMD160::InitState(HashWordType *state) { - m_digest[0] = 0x67452301L; - m_digest[1] = 0xefcdab89L; - m_digest[2] = 0x98badcfeL; - m_digest[3] = 0x10325476L; - m_digest[4] = 0xc3d2e1f0L; + state[0] = 0x67452301L; + state[1] = 0xefcdab89L; + state[2] = 0x98badcfeL; + state[3] = 0x10325476L; + state[4] = 0xc3d2e1f0L; } void RIPEMD160::Transform (word32 *digest, const word32 *X) @@ -232,18 +232,18 @@ void RIPEMD160::Transform (word32 *digest, const word32 *X) // ************************************************************* -void RIPEMD320::Init() +void RIPEMD320::InitState(HashWordType *state) { - m_digest[0] = 0x67452301L; - m_digest[1] = 0xefcdab89L; - m_digest[2] = 0x98badcfeL; - m_digest[3] = 0x10325476L; - m_digest[4] = 0xc3d2e1f0L; - m_digest[5] = 0x76543210L; - m_digest[6] = 0xfedcba98L; - m_digest[7] = 0x89abcdefL; - m_digest[8] = 0x01234567L; - m_digest[9] = 0x3c2d1e0fL; + state[0] = 0x67452301L; + state[1] = 0xefcdab89L; + state[2] = 0x98badcfeL; + state[3] = 0x10325476L; + state[4] = 0xc3d2e1f0L; + state[5] = 0x76543210L; + state[6] = 0xfedcba98L; + state[7] = 0x89abcdefL; + state[8] = 0x01234567L; + state[9] = 0x3c2d1e0fL; } void RIPEMD320::Transform (word32 *digest, const word32 *X) @@ -461,12 +461,12 @@ void RIPEMD320::Transform (word32 *digest, const word32 *X) a += f(b, c, d) + x + k;\ a = rotlFixed((word32)a, s); -void RIPEMD128::Init() +void RIPEMD128::InitState(HashWordType *state) { - m_digest[0] = 0x67452301L; - m_digest[1] = 0xefcdab89L; - m_digest[2] = 0x98badcfeL; - m_digest[3] = 0x10325476L; + state[0] = 0x67452301L; + state[1] = 0xefcdab89L; + state[2] = 0x98badcfeL; + state[3] = 0x10325476L; } void RIPEMD128::Transform (word32 *digest, const word32 *X) @@ -622,16 +622,16 @@ void RIPEMD128::Transform (word32 *digest, const word32 *X) // ************************************************************* -void RIPEMD256::Init() +void RIPEMD256::InitState(HashWordType *state) { - m_digest[0] = 0x67452301L; - m_digest[1] = 0xefcdab89L; - m_digest[2] = 0x98badcfeL; - m_digest[3] = 0x10325476L; - m_digest[4] = 0x76543210L; - m_digest[5] = 0xfedcba98L; - m_digest[6] = 0x89abcdefL; - m_digest[7] = 0x01234567L; + state[0] = 0x67452301L; + state[1] = 0xefcdab89L; + state[2] = 0x98badcfeL; + state[3] = 0x10325476L; + state[4] = 0x76543210L; + state[5] = 0xfedcba98L; + state[6] = 0x89abcdefL; + state[7] = 0x01234567L; } void RIPEMD256::Transform (word32 *digest, const word32 *X) diff --git a/ripemd.h b/ripemd.h index f128158c..40fd8f4f 100644 --- a/ripemd.h +++ b/ripemd.h @@ -7,55 +7,39 @@ NAMESPACE_BEGIN(CryptoPP) //! RIPEMD-160 /*! Digest Length = 160 bits */ -class RIPEMD160 : public IteratedHashWithStaticTransform +class RIPEMD160 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 20}; - RIPEMD160() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char * StaticAlgorithmName() {return "RIPEMD-160";} - -protected: - void Init(); }; /*! Digest Length = 320 bits, Security = 160 bits */ -class RIPEMD320 : public IteratedHashWithStaticTransform +class RIPEMD320 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 40}; - RIPEMD320() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char * StaticAlgorithmName() {return "RIPEMD-320";} - -protected: - void Init(); }; /*! Digest Length = 128 bits */ -class RIPEMD128 : public IteratedHashWithStaticTransform +class RIPEMD128 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 16}; - RIPEMD128() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char * StaticAlgorithmName() {return "RIPEMD-128";} - -protected: - void Init(); }; /*! Digest Length = 256 bits, Security = 128 bits */ -class RIPEMD256 : public IteratedHashWithStaticTransform +class RIPEMD256 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 32}; - RIPEMD256() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char * StaticAlgorithmName() {return "RIPEMD-256";} - -protected: - void Init(); }; NAMESPACE_END diff --git a/rng.cpp b/rng.cpp index dfcd2629..2cd5db40 100644 --- a/rng.cpp +++ b/rng.cpp @@ -1,6 +1,7 @@ // rng.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + #include "rng.h" #include @@ -51,6 +52,8 @@ byte LC_RNG::GenerateByte() // ******************************************************** +#ifndef CRYPTOPP_IMPORTS + X917RNG::X917RNG(BlockTransformation *c, const byte *seed, unsigned long deterministicTimeVector) : cipher(c), S(cipher->BlockSize()), @@ -109,6 +112,8 @@ byte X917RNG::GenerateByte() return(randbuf[--randbuf_counter]); } +#endif + MaurerRandomnessTest::MaurerRandomnessTest() : sum(0.0), n(0) { diff --git a/rng.h b/rng.h index 1ca082e5..097cae77 100644 --- a/rng.h +++ b/rng.h @@ -1,3 +1,5 @@ +// rng.h - misc RNG related classes, see also osrng.h, randpool.h + #ifndef CRYPTOPP_RNG_H #define CRYPTOPP_RNG_H @@ -29,7 +31,7 @@ private: //! RNG derived from ANSI X9.17 Appendix C -class X917RNG : public RandomNumberGenerator +class CRYPTOPP_DLL X917RNG : public RandomNumberGenerator, public NotCopyable { public: // cipher will be deleted by destructor, deterministicTimeVector = 0 means obtain time vector from system diff --git a/rsa.cpp b/rsa.cpp index 76d4aa9a..4ed1ca0f 100644 --- a/rsa.cpp +++ b/rsa.cpp @@ -10,15 +10,15 @@ #include "algparam.h" #include "fips140.h" -#ifndef NDEBUG +#if !defined(NDEBUG) && defined(CRYPTOPP_NO_DLL) #include "pssr.h" #endif -#include "oaep.cpp" - NAMESPACE_BEGIN(CryptoPP) -#ifndef NDEBUG +byte OAEP_P_DEFAULT[1]; + +#if !defined(NDEBUG) && defined(CRYPTOPP_NO_DLL) void RSA_TestInstantiations() { RSASS::Verifier x1(1, 1); @@ -41,7 +41,7 @@ void RSA_TestInstantiations() } #endif -template class OAEP; +#ifndef CRYPTOPP_IMPORTS OID RSAFunction::GetAlgorithmID() const { @@ -278,4 +278,6 @@ void InvertibleRSAFunction::AssignFrom(const NameValuePairs &source) ; } +#endif + NAMESPACE_END diff --git a/rsa.h b/rsa.h index 7f821340..cae0a5a7 100644 --- a/rsa.h +++ b/rsa.h @@ -14,7 +14,7 @@ NAMESPACE_BEGIN(CryptoPP) //! . -class RSAFunction : public TrapdoorFunction, public X509PublicKey +class CRYPTOPP_DLL RSAFunction : public TrapdoorFunction, public X509PublicKey { typedef RSAFunction ThisClass; @@ -49,7 +49,7 @@ protected: }; //! . -class InvertibleRSAFunction : public RSAFunction, public TrapdoorFunctionInverse, public PKCS8PrivateKey +class CRYPTOPP_DLL InvertibleRSAFunction : public RSAFunction, public TrapdoorFunctionInverse, public PKCS8PrivateKey { typedef InvertibleRSAFunction ThisClass; @@ -101,7 +101,7 @@ protected: }; //! . -struct RSA +struct CRYPTOPP_DLL RSA { static std::string StaticAlgorithmName() {return "RSA";} typedef RSAFunction PublicKey; diff --git a/safer.h b/safer.h index 943c1cec..d9a477cf 100644 --- a/safer.h +++ b/safer.h @@ -47,21 +47,21 @@ struct SAFER_K_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 8, /// SAFER-K class SAFER_K : public SAFER_K_Info, public SAFER, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Enc : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Enc : public BlockCipherImpl { public: Enc() {strengthened = false;} }; - class CRYPTOPP_NO_VTABLE Dec : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Dec : public BlockCipherImpl { public: Dec() {strengthened = false;} }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; struct SAFER_SK_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 8, 16, 8>, public VariableRounds<10, 1, 13> @@ -73,21 +73,21 @@ struct SAFER_SK_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 8, /// SAFER-SK class SAFER_SK : public SAFER_SK_Info, public SAFER, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Enc : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Enc : public BlockCipherImpl { public: Enc() {strengthened = true;} }; - class CRYPTOPP_NO_VTABLE Dec : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Dec : public BlockCipherImpl { public: Dec() {strengthened = true;} }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef SAFER_K::Encryption SAFER_K_Encryption; diff --git a/seal.h b/seal.h index 42b6ec16..2e190026 100644 --- a/seal.h +++ b/seal.h @@ -38,7 +38,7 @@ private: template struct SEAL : public SEAL_Info, public SymmetricCipherDocumentation { - typedef SymmetricCipherFinalTemplate, AdditiveCipherTemplate<> >, SEAL_Info > Encryption; + typedef SymmetricCipherFinal, AdditiveCipherTemplate<> >, SEAL_Info > Encryption; typedef Encryption Decryption; }; diff --git a/secblock.h b/secblock.h index e07c6a21..580aab7a 100644 --- a/secblock.h +++ b/secblock.h @@ -18,7 +18,7 @@ class AllocatorBase public: typedef T value_type; typedef size_t size_type; -#if (defined(_MSC_VER) && _MSC_VER < 1300) +#ifdef CRYPTOPP_MSVCRT6 typedef ptrdiff_t difference_type; #else typedef std::ptrdiff_t difference_type; @@ -94,6 +94,10 @@ public: template struct rebind { typedef AllocatorWithCleanup other; }; }; +CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup; +CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup; +CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup; + template class NullAllocator : public AllocatorBase { @@ -325,7 +329,12 @@ public: m_size = newSize; } - void swap(SecBlock &b); + void swap(SecBlock &b) + { + std::swap(m_alloc, b.m_alloc); + std::swap(m_size, b.m_size); + std::swap(m_ptr, b.m_ptr); + } //private: A m_alloc; @@ -333,13 +342,6 @@ public: T *m_ptr; }; -template void SecBlock::swap(SecBlock &b) -{ - std::swap(m_alloc, b.m_alloc); - std::swap(m_size, b.m_size); - std::swap(m_ptr, b.m_ptr); -} - typedef SecBlock SecByteBlock; typedef SecBlock SecWordBlock; diff --git a/seckey.h b/seckey.h index 0b173459..e00fa89f 100644 --- a/seckey.h +++ b/seckey.h @@ -18,7 +18,7 @@ inline CipherDir ReverseCipherDir(CipherDir dir) //! . template -class FixedBlockSize +class CRYPTOPP_DLL FixedBlockSize { public: enum {BLOCKSIZE = N}; @@ -28,7 +28,7 @@ public: //! . template -class FixedRounds +class CRYPTOPP_DLL FixedRounds { public: enum {ROUNDS = R}; @@ -47,7 +47,7 @@ protected: //! . template // use INT_MAX here because enums are treated as signed ints -class VariableRounds +class CRYPTOPP_DLL VariableRounds { public: enum {DEFAULT_ROUNDS = D, MIN_ROUNDS = N, MAX_ROUNDS = M}; @@ -74,7 +74,7 @@ protected: //! . template -class FixedKeyLength +class CRYPTOPP_DLL FixedKeyLength { public: enum {KEYLENGTH=N, MIN_KEYLENGTH=N, MAX_KEYLENGTH=N, DEFAULT_KEYLENGTH=N}; @@ -84,7 +84,7 @@ public: /// support query of variable key length, template parameters are default, min, max, multiple (default multiple 1) template -class VariableKeyLength +class CRYPTOPP_DLL VariableKeyLength { // make these private to avoid Doxygen documenting them in all derived classes CRYPTOPP_COMPILE_ASSERT(Q > 0); @@ -112,7 +112,7 @@ public: /// support query of key length that's the same as another class template -class SameKeyLengthAs +class CRYPTOPP_DLL SameKeyLengthAs { public: enum {MIN_KEYLENGTH=T::MIN_KEYLENGTH, MAX_KEYLENGTH=T::MAX_KEYLENGTH, DEFAULT_KEYLENGTH=T::DEFAULT_KEYLENGTH}; @@ -152,8 +152,8 @@ protected: void AssertValidKeyLength(unsigned int length) {assert(GetValidKeyLength(length) == length);} }; -template -class CRYPTOPP_NO_VTABLE BlockCipherBaseTemplate : public AlgorithmImpl > > +template +class CRYPTOPP_NO_VTABLE BlockCipherImpl : public AlgorithmImpl, INFO>, public INFO { public: unsigned int BlockSize() const {return BLOCKSIZE;} @@ -161,15 +161,15 @@ public: //! . template -class BlockCipherTemplate : public BASE +class BlockCipherFinal : public ClonableImpl, BASE> { public: - BlockCipherTemplate() {} - BlockCipherTemplate(const byte *key) + BlockCipherFinal() {} + BlockCipherFinal(const byte *key) {SetKey(key, DEFAULT_KEYLENGTH);} - BlockCipherTemplate(const byte *key, unsigned int length) + BlockCipherFinal(const byte *key, unsigned int length) {SetKey(key, length);} - BlockCipherTemplate(const byte *key, unsigned int length, unsigned int rounds) + BlockCipherFinal(const byte *key, unsigned int length, unsigned int rounds) {SetKeyWithRounds(key, length, rounds);} bool IsForwardTransformation() const {return DIR == ENCRYPTION;} @@ -178,34 +178,34 @@ public: { CheckedSetKey(this, DIR, key, length, param); } - - Clonable * Clone() const {return new BlockCipherTemplate(*this);} }; //! . -template -class MessageAuthenticationCodeTemplate : public +template +class MessageAuthenticationCodeImpl : public #ifdef CRYPTOPP_DOXYGEN_PROCESSING MessageAuthenticationCode #else - SimpleKeyingInterfaceImpl + AlgorithmImpl, INFO> #endif { public: - MessageAuthenticationCodeTemplate() {} - MessageAuthenticationCodeTemplate(const byte *key) - {SetKey(key, DEFAULT_KEYLENGTH);} - MessageAuthenticationCodeTemplate(const byte *key, unsigned int length) - {SetKey(key, length);} - - std::string AlgorithmName() const {return StaticAlgorithmName();} - void SetKey(const byte *key, unsigned int length, const NameValuePairs ¶m = g_nullNameValuePairs) { CheckedSetKey(this, Empty(), key, length, param); } +}; - Clonable * Clone() const {return new MessageAuthenticationCodeTemplate(*this);} +//! . +template +class MessageAuthenticationCodeFinal : public ClonableImpl, MessageAuthenticationCodeImpl > +{ +public: + MessageAuthenticationCodeFinal() {} + MessageAuthenticationCodeFinal(const byte *key) + {SetKey(key, DEFAULT_KEYLENGTH);} + MessageAuthenticationCodeFinal(const byte *key, unsigned int length) + {SetKey(key, length);} }; // ************** documentation *************** diff --git a/serpent.h b/serpent.h index 6bc2f89d..0d245114 100644 --- a/serpent.h +++ b/serpent.h @@ -17,7 +17,7 @@ struct Serpent_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 1, /// Serpent class Serpent : public Serpent_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -39,8 +39,8 @@ class Serpent : public Serpent_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Serpent::Encryption SerpentEncryption; diff --git a/sha.cpp b/sha.cpp index 958d9ea0..4eaae566 100644 --- a/sha.cpp +++ b/sha.cpp @@ -4,25 +4,28 @@ // Both are in the public domain. #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "sha.h" #include "misc.h" NAMESPACE_BEGIN(CryptoPP) -void SHA::Init() -{ - m_digest[0] = 0x67452301L; - m_digest[1] = 0xEFCDAB89L; - m_digest[2] = 0x98BADCFEL; - m_digest[3] = 0x10325476L; - m_digest[4] = 0xC3D2E1F0L; -} - // start of Steve Reid's code #define blk0(i) (W[i] = data[i]) #define blk1(i) (W[i&15] = rotlFixed(W[(i+13)&15]^W[(i+8)&15]^W[(i+2)&15]^W[i&15],1)) +void SHA::InitState(HashWordType *state) +{ + state[0] = 0x67452301L; + state[1] = 0xEFCDAB89L; + state[2] = 0x98BADCFEL; + state[3] = 0x10325476L; + state[4] = 0xC3D2E1F0L; +} + #define f1(x,y,z) (z^(x&(y^z))) #define f2(x,y,z) (x^y^z) #define f3(x,y,z) ((x&y)|(z&(x|y))) @@ -80,16 +83,16 @@ void SHA::Transform(word32 *state, const word32 *data) // ************************************************************* -void SHA256::Init() +void SHA256::InitState(HashWordType *state) { - m_digest[0] = 0x6a09e667; - m_digest[1] = 0xbb67ae85; - m_digest[2] = 0x3c6ef372; - m_digest[3] = 0xa54ff53a; - m_digest[4] = 0x510e527f; - m_digest[5] = 0x9b05688c; - m_digest[6] = 0x1f83d9ab; - m_digest[7] = 0x5be0cd19; + state[0] = 0x6a09e667; + state[1] = 0xbb67ae85; + state[2] = 0x3c6ef372; + state[3] = 0xa54ff53a; + state[4] = 0x510e527f; + state[5] = 0x9b05688c; + state[6] = 0x1f83d9ab; + state[7] = 0x5be0cd19; } #define blk2(i) (W[i&15]+=s1(W[(i-2)&15])+W[(i-7)&15]+s0(W[(i-15)&15])) @@ -171,16 +174,16 @@ const word32 SHA256::K[64] = { #ifdef WORD64_AVAILABLE -void SHA512::Init() +void SHA512::InitState(HashWordType *state) { - m_digest[0] = W64LIT(0x6a09e667f3bcc908); - m_digest[1] = W64LIT(0xbb67ae8584caa73b); - m_digest[2] = W64LIT(0x3c6ef372fe94f82b); - m_digest[3] = W64LIT(0xa54ff53a5f1d36f1); - m_digest[4] = W64LIT(0x510e527fade682d1); - m_digest[5] = W64LIT(0x9b05688c2b3e6c1f); - m_digest[6] = W64LIT(0x1f83d9abfb41bd6b); - m_digest[7] = W64LIT(0x5be0cd19137e2179); + state[0] = W64LIT(0x6a09e667f3bcc908); + state[1] = W64LIT(0xbb67ae8584caa73b); + state[2] = W64LIT(0x3c6ef372fe94f82b); + state[3] = W64LIT(0xa54ff53a5f1d36f1); + state[4] = W64LIT(0x510e527fade682d1); + state[5] = W64LIT(0x9b05688c2b3e6c1f); + state[6] = W64LIT(0x1f83d9abfb41bd6b); + state[7] = W64LIT(0x5be0cd19137e2179); } // for SHA512 @@ -260,18 +263,20 @@ const word64 SHA512::K[80] = { W64LIT(0x5fcb6fab3ad6faec), W64LIT(0x6c44198c4a475817) }; -void SHA384::Init() +void SHA384::InitState(HashWordType *state) { - m_digest[0] = W64LIT(0xcbbb9d5dc1059ed8); - m_digest[1] = W64LIT(0x629a292a367cd507); - m_digest[2] = W64LIT(0x9159015a3070dd17); - m_digest[3] = W64LIT(0x152fecd8f70e5939); - m_digest[4] = W64LIT(0x67332667ffc00b31); - m_digest[5] = W64LIT(0x8eb44a8768581511); - m_digest[6] = W64LIT(0xdb0c2e0d64f98fa7); - m_digest[7] = W64LIT(0x47b5481dbefa4fa4); + state[0] = W64LIT(0xcbbb9d5dc1059ed8); + state[1] = W64LIT(0x629a292a367cd507); + state[2] = W64LIT(0x9159015a3070dd17); + state[3] = W64LIT(0x152fecd8f70e5939); + state[4] = W64LIT(0x67332667ffc00b31); + state[5] = W64LIT(0x8eb44a8768581511); + state[6] = W64LIT(0xdb0c2e0d64f98fa7); + state[7] = W64LIT(0x47b5481dbefa4fa4); } #endif NAMESPACE_END + +#endif diff --git a/sha.h b/sha.h index 9c1cce5a..f7936761 100644 --- a/sha.h +++ b/sha.h @@ -6,63 +6,49 @@ NAMESPACE_BEGIN(CryptoPP) /// SHA-1 -class SHA : public IteratedHashWithStaticTransform +class CRYPTOPP_DLL SHA : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 20}; - SHA() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char *StaticAlgorithmName() {return "SHA-1";} - -protected: - void Init(); }; typedef SHA SHA1; //! implements the SHA-256 standard -class SHA256 : public IteratedHashWithStaticTransform +class CRYPTOPP_DLL SHA256 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 32}; - SHA256() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word32 *digest, const word32 *data); static const char *StaticAlgorithmName() {return "SHA-256";} protected: - void Init(); - static const word32 K[64]; }; #ifdef WORD64_AVAILABLE //! implements the SHA-512 standard -class SHA512 : public IteratedHashWithStaticTransform +class CRYPTOPP_DLL SHA512 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 64}; - SHA512() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word64 *digest, const word64 *data); static const char *StaticAlgorithmName() {return "SHA-512";} protected: - void Init(); - static const word64 K[80]; }; //! implements the SHA-384 standard -class SHA384 : public IteratedHashWithStaticTransform +class CRYPTOPP_DLL SHA384 : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 48}; - SHA384() : IteratedHashWithStaticTransform(64) {Init();} - unsigned int DigestSize() const {return DIGESTSIZE;}; + static void InitState(HashWordType *state); + static void Transform(word64 *digest, const word64 *data) {SHA512::Transform(digest, data);} static const char *StaticAlgorithmName() {return "SHA-384";} - -protected: - void Init(); }; #endif diff --git a/shacal2.h b/shacal2.h index fedbe79f..554c925a 100644 --- a/shacal2.h +++ b/shacal2.h @@ -17,7 +17,7 @@ struct SHACAL2_Info : public FixedBlockSize<32>, public VariableKeyLength<16, 16 /// SHACAL-2 class SHACAL2 : public SHACAL2_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -41,8 +41,8 @@ class SHACAL2 : public SHACAL2_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef SHACAL2::Encryption SHACAL2Encryption; diff --git a/shark.h b/shark.h index f67de109..513eb897 100644 --- a/shark.h +++ b/shark.h @@ -21,7 +21,7 @@ struct SHARK_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 1, 16 /// SHARK-E class SHARK : public SHARK_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length, unsigned int rounds); @@ -55,8 +55,8 @@ class SHARK : public SHARK_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef SHARK::Encryption SHARKEncryption; diff --git a/simple.cpp b/simple.cpp index ee5ab0cb..96f256b4 100644 --- a/simple.cpp +++ b/simple.cpp @@ -1,23 +1,14 @@ // simple.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "simple.h" #include "secblock.h" NAMESPACE_BEGIN(CryptoPP) -void HashTransformationWithDefaultTruncation::TruncatedFinal(byte *digest, unsigned int digestSize) -{ - ThrowIfInvalidTruncatedSize(digestSize); - unsigned int fullDigestSize = DigestSize(); - if (digestSize == fullDigestSize) - Final(digest); - else - { - SecByteBlock buffer(fullDigestSize); - Final(buffer); - memcpy(digest, buffer, digestSize); - } -} - NAMESPACE_END + +#endif diff --git a/simple.h b/simple.h index 1727d381..0185a26e 100644 --- a/simple.h +++ b/simple.h @@ -11,6 +11,13 @@ NAMESPACE_BEGIN(CryptoPP) +template +class CRYPTOPP_NO_VTABLE ClonableImpl : public BASE +{ +public: + Clonable * Clone() const {return new DERIVED(*static_cast(this));} +}; + template class CRYPTOPP_NO_VTABLE AlgorithmImpl : public BASE { @@ -19,29 +26,22 @@ public: }; //! . -class InvalidKeyLength : public InvalidArgument +class CRYPTOPP_DLL InvalidKeyLength : public InvalidArgument { public: explicit InvalidKeyLength(const std::string &algorithm, unsigned int length) : InvalidArgument(algorithm + ": " + IntToString(length) + " is not a valid key length") {} }; //! . -class InvalidRounds : public InvalidArgument +class CRYPTOPP_DLL InvalidRounds : public InvalidArgument { public: explicit InvalidRounds(const std::string &algorithm, unsigned int rounds) : InvalidArgument(algorithm + ": " + IntToString(rounds) + " is not a valid number of rounds") {} }; -class CRYPTOPP_NO_VTABLE HashTransformationWithDefaultTruncation : public HashTransformation -{ -public: - virtual void Final(byte *digest) =0; - void TruncatedFinal(byte *digest, unsigned int digestSize); -}; - //! . // TODO: look into this virtual inheritance -class ASN1CryptoMaterial : virtual public ASN1Object, virtual public CryptoMaterial +class CRYPTOPP_DLL ASN1CryptoMaterial : virtual public ASN1Object, virtual public CryptoMaterial { public: void Save(BufferedTransformation &bt) const @@ -175,7 +175,7 @@ private: }; //! A BufferedTransformation that only contains pre-existing data as "output" -class CRYPTOPP_NO_VTABLE Store : public AutoSignaling > +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Store : public AutoSignaling > { public: Store() : m_messageEnd(false) {} @@ -197,7 +197,7 @@ protected: }; //! A BufferedTransformation that doesn't produce any retrievable output -class CRYPTOPP_NO_VTABLE Sink : public BufferedTransformation +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Sink : public BufferedTransformation { protected: // make these functions protected to help prevent unintentional calls to them @@ -216,7 +216,7 @@ protected: {return 0;} }; -class BitBucket : public Bufferless +class CRYPTOPP_DLL BitBucket : public Bufferless { public: std::string AlgorithmName() const {return "BitBucket";} diff --git a/skipjack.cpp b/skipjack.cpp index 10c53c99..0fb472d1 100644 --- a/skipjack.cpp +++ b/skipjack.cpp @@ -2,6 +2,9 @@ // which is public domain according to his web site. #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "skipjack.h" /* @@ -195,3 +198,5 @@ void SKIPJACK::Dec::ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock } NAMESPACE_END + +#endif diff --git a/skipjack.h b/skipjack.h index 99e19fc2..fbec2df1 100644 --- a/skipjack.h +++ b/skipjack.h @@ -11,13 +11,13 @@ NAMESPACE_BEGIN(CryptoPP) struct SKIPJACK_Info : public FixedBlockSize<8>, public FixedKeyLength<10> { - static const char *StaticAlgorithmName() {return "SKIPJACK";} + CRYPTOPP_DLL static const char * StaticAlgorithmName() {return "SKIPJACK";} }; /// SKIPJACK class SKIPJACK : public SKIPJACK_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -28,7 +28,7 @@ class SKIPJACK : public SKIPJACK_Info, public BlockCipherDocumentation FixedSizeSecBlock tab; }; - class CRYPTOPP_NO_VTABLE Enc : public Base + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Enc : public Base { public: void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; @@ -37,7 +37,7 @@ class SKIPJACK : public SKIPJACK_Info, public BlockCipherDocumentation static const word32 Te[4][256]; }; - class CRYPTOPP_NO_VTABLE Dec : public Base + class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Dec : public Base { public: void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; @@ -47,8 +47,8 @@ class SKIPJACK : public SKIPJACK_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef SKIPJACK::Encryption SKIPJACKEncryption; diff --git a/square.h b/square.h index 236fcaa1..8746059a 100644 --- a/square.h +++ b/square.h @@ -17,7 +17,7 @@ struct Square_Info : public FixedBlockSize<16>, public FixedKeyLength<16>, Fixed /// Square class Square : public Square_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -45,8 +45,8 @@ class Square : public Square_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Square::Encryption SquareEncryption; diff --git a/stdcpp.h b/stdcpp.h new file mode 100644 index 00000000..5a13a32d --- /dev/null +++ b/stdcpp.h @@ -0,0 +1,31 @@ +#ifndef CRYPTOPP_STDCPP_H +#define CRYPTOPP_STDCPP_H + +#include +#include +#include +#include +#include +#include +#include + + +#ifdef _MSC_VER +#include // CodeWarrior doesn't have memory.h +#include +#include +#include +#include +#include +#include +#include + +// re-disable this +#pragma warning(disable: 4231) +#endif + +#if defined(_MSC_VER) && defined(_CRTAPI1) +#define CRYPTOPP_MSVCRT6 +#endif + +#endif diff --git a/strciphr.cpp b/strciphr.cpp index d948c579..1f03d4c5 100644 --- a/strciphr.cpp +++ b/strciphr.cpp @@ -1,6 +1,9 @@ // strciphr.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "strciphr.h" NAMESPACE_BEGIN(CryptoPP) @@ -186,3 +189,5 @@ void CFB_DecryptionTemplate::CombineMessageAndShiftRegister(byte *output, } NAMESPACE_END + +#endif diff --git a/strciphr.h b/strciphr.h index bef2f7ea..3e0a739a 100644 --- a/strciphr.h +++ b/strciphr.h @@ -14,14 +14,14 @@ (since it's an additive cipher, i.e., it xors a keystream into the plaintext). See this line in seal.h: - typedef SymmetricCipherFinalTemplate, AdditiveCipherTemplate<> > > Encryption; + typedef SymmetricCipherFinal, AdditiveCipherTemplate<> > > Encryption; AdditiveCipherTemplate and CFB_CipherTemplate are designed so that they don't need to take a policy class as a template parameter (although this is allowed), so that their code is not duplicated for each new cipher. Instead they each get a reference to an abstract policy interface by calling AccessPolicy() on itself, so AccessPolicy() must be overriden to return the actual policy reference. This is done - by the ConceretePolicyHolder class. Finally, SymmetricCipherFinalTemplate implements the constructors and + by the ConceretePolicyHolder class. Finally, SymmetricCipherFinal implements the constructors and other functions that must be implemented by the most derived class. */ @@ -55,7 +55,7 @@ protected: enum KeystreamOperation {WRITE_KEYSTREAM, XOR_KEYSTREAM, XOR_KEYSTREAM_INPLACE}; -struct CRYPTOPP_NO_VTABLE AdditiveCipherAbstractPolicy +struct CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AdditiveCipherAbstractPolicy { virtual unsigned int GetAlignment() const =0; virtual unsigned int GetBytesPerIteration() const =0; @@ -146,8 +146,13 @@ protected: unsigned int m_leftOver; }; -struct CRYPTOPP_NO_VTABLE CFB_CipherAbstractPolicy +CRYPTOPP_DLL_TEMPLATE_CLASS TwoBases; +CRYPTOPP_DLL_TEMPLATE_CLASS AbstractPolicyHolder >; +CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<>; + +class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_CipherAbstractPolicy { +public: virtual unsigned int GetAlignment() const =0; virtual unsigned int GetBytesPerIteration() const =0; virtual byte * GetRegisterBegin() =0; @@ -246,16 +251,21 @@ class CRYPTOPP_NO_VTABLE CFB_DecryptionTemplate : public CFB_CipherTemplate; +CRYPTOPP_DLL_TEMPLATE_CLASS CFB_CipherTemplate >; +CRYPTOPP_DLL_TEMPLATE_CLASS CFB_EncryptionTemplate<>; +CRYPTOPP_DLL_TEMPLATE_CLASS CFB_DecryptionTemplate<>; + template -class SymmetricCipherFinalTemplate : public AlgorithmImpl, INFO> +class SymmetricCipherFinal : public AlgorithmImpl, INFO> { public: - SymmetricCipherFinalTemplate() {} - SymmetricCipherFinalTemplate(const byte *key) + SymmetricCipherFinal() {} + SymmetricCipherFinal(const byte *key) {SetKey(key, DEFAULT_KEYLENGTH);} - SymmetricCipherFinalTemplate(const byte *key, unsigned int length) + SymmetricCipherFinal(const byte *key, unsigned int length) {SetKey(key, length);} - SymmetricCipherFinalTemplate(const byte *key, unsigned int length, const byte *iv) + SymmetricCipherFinal(const byte *key, unsigned int length, const byte *iv) {SetKeyWithIV(key, length, iv);} void SetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms = g_nullNameValuePairs) @@ -264,7 +274,7 @@ public: UncheckedSetKey(params, key, length, GetIVAndThrowIfInvalid(params)); } - Clonable * Clone() const {return static_cast(new SymmetricCipherFinalTemplate(*this));} + Clonable * Clone() const {return static_cast(new SymmetricCipherFinal(*this));} }; template diff --git a/tea.h b/tea.h index 397db26b..79277437 100644 --- a/tea.h +++ b/tea.h @@ -18,7 +18,7 @@ struct TEA_Info : public FixedBlockSize<8>, public FixedKeyLength<16>, public Fi /// TEA class TEA : public TEA_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -41,8 +41,8 @@ class TEA : public TEA_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef TEA::Encryption TEAEncryption; diff --git a/test.cpp b/test.cpp index cc871d48..2aea6077 100644 --- a/test.cpp +++ b/test.cpp @@ -1,6 +1,6 @@ // test.cpp - written and placed in the public domain by Wei Dai -#include "pch.h" +#include "dll.h" #include "md5.h" #include "sha.h" #include "ripemd.h" @@ -56,6 +56,7 @@ void RSASignFile(const char *privFilename, const char *messageFilename, const ch bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename); void DigestFile(const char *file); +void HmacFile(const char *hexKey, const char *file); string EncryptString(const char *plaintext, const char *passPhrase); string DecryptString(const char *ciphertext, const char *passPhrase); @@ -79,7 +80,7 @@ void HexDecode(const char *in, const char *out); void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort); -void FIPS140_SampleApplication(const char *moduleFilename, const char *edcFilename); +void FIPS140_SampleApplication(); void FIPS140_GenerateRandomFiles(); bool Validate(int, bool, const char *); @@ -110,37 +111,13 @@ int main(int argc, char *argv[]) try { - std::string command, executableName, edcFilename; + std::string command, executableName, macFilename; if (argc < 2) command = 'h'; else command = argv[1]; - if (FIPS_140_2_ComplianceEnabled()) - { - edcFilename = "edc.dat"; - -#ifdef CRYPTOPP_WIN32_AVAILABLE - TCHAR filename[MAX_PATH]; - GetModuleFileName(GetModuleHandle(NULL), filename, sizeof(filename)); - executableName = filename; - std::string::size_type pos = executableName.rfind('\\'); - if (pos != std::string::npos) - edcFilename = executableName.substr(0, pos+1) + edcFilename; -#else - executableName = argv[0]; -#endif - - if (command.substr(0, 4) != "fips") - { - byte expectedModuleDigest[SHA1::DIGESTSIZE]; - FileSource(edcFilename.c_str(), true, new HexDecoder(new ArraySink(expectedModuleDigest, sizeof(expectedModuleDigest)))); - - DoPowerUpSelfTest(executableName.c_str(), expectedModuleDigest); - } - } - switch (command[0]) { case 'g': @@ -206,7 +183,44 @@ int main(int argc, char *argv[]) } } case 'm': - if (command == "mt") + if (command == "mac_dll") + { + HMODULE hModule = LoadLibrary(argv[2]); + PGetPowerUpSelfTestStatus pGetPowerUpSelfTestStatus = (PGetPowerUpSelfTestStatus)GetProcAddress(hModule, "?GetPowerUpSelfTestStatus@CryptoPP@@YG?AW4PowerUpSelfTestStatus@1@XZ"); + PGetActualMacAndLocation pGetActualMacAndLocation = (PGetActualMacAndLocation)GetProcAddress(hModule, "?GetActualMacAndLocation@CryptoPP@@YGPBEAAI0@Z"); + + PowerUpSelfTestStatus status = pGetPowerUpSelfTestStatus(); + if (status == POWER_UP_SELF_TEST_PASSED) + { + cout << "Crypto++ DLL MAC is valid. Nothing to do.\n"; + return 0; + } + + unsigned int macSize, macFileLocation; + const byte *pMac = pGetActualMacAndLocation(macSize, macFileLocation); + + if (macFileLocation == 0) + { + cerr << "Could not find MAC location in Crypto++ DLL.\n"; + return 1; + } + else + { + SecByteBlock mac(pMac, macSize); // copy MAC before freeing the DLL + BOOL r = FreeLibrary(hModule); + cout << "Placing MAC in file " << argv[2] << ", location " << macFileLocation << ".\n"; + std::ofstream dllFile(argv[2], ios::in | ios::out | ios::binary); + dllFile.seekp(macFileLocation); + dllFile.write((const char *)mac.data(), macSize); + if (!dllFile.good()) + { + cerr << "Error writing file.\n"; + return 1; + } + return 0; + } + } + else if (command == "mt") { MaurerRandomnessTest mt; FileStore fs(argv[2]); @@ -294,7 +308,7 @@ int main(int argc, char *argv[]) return 0; case 'f': if (command == "fips") - FIPS140_SampleApplication(executableName.c_str(), edcFilename.c_str()); + FIPS140_SampleApplication(); else if (command == "fips-rand") FIPS140_GenerateRandomFiles(); else if (command == "ft") @@ -305,6 +319,13 @@ int main(int argc, char *argv[]) return (*AdhocTest)(argc, argv); else return 0; + case 'h': + if (command == "hmac") + { + HmacFile(argv[2], argv[3]); + return 0; + } + // fall through default: FileSource usage("usage.dat", true, new FileSink(cout)); return 1; @@ -322,180 +343,6 @@ int main(int argc, char *argv[]) } } -void FIPS140_SampleApplication(const char *moduleFilename, const char *edcFilename) -{ - if (!FIPS_140_2_ComplianceEnabled()) - { - cerr << "FIPS-140-2 compliance was turned off at compile time.\n"; - abort(); - } - - // try to use a crypto algorithm before doing a self test - try - { - // trying to use a crypto algorithm before power-up self test will result in an exception - DES::Encryption des; - - // should not be here - cerr << "Use of DES before power-up test failed to cause an exception.\n"; - abort(); - } - catch (SelfTestFailure &e) - { - cout << "0. Caught expected exception. Exception message follows: "; - cout << e.what() << endl; - } - - // simulate a power-up self test error - SimulatePowerUpSelfTestFailure(); - try - { - // trying to use a crypto algorithm after power-up self test error will result in an exception - DES::Encryption des; - - // should not be here - cerr << "Use of DES failed to cause an exception after power-up self test error.\n"; - abort(); - } - catch (SelfTestFailure &e) - { - cout << "1. Caught expected exception when simulating self test failure. Exception message follows: "; - cout << e.what() << endl; - } - - // clear the self test error state and do power-up self test - byte expectedModuleDigest[SHA1::DIGESTSIZE]; - FileSource(edcFilename, true, new HexDecoder(new ArraySink(expectedModuleDigest, sizeof(expectedModuleDigest)))); - - DoPowerUpSelfTest(moduleFilename, expectedModuleDigest); - if (GetPowerUpSelfTestStatus() != POWER_UP_SELF_TEST_PASSED) - { - cerr << "Power-up self test failed.\n"; - abort(); - } - cout << "2. Power-up self test passed.\n"; - - // encrypt and decrypt - const byte key[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; - const byte iv[] = {0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef}; - const byte plaintext[] = { // "Now is the time for all " without tailing 0 - 0x4e,0x6f,0x77,0x20,0x69,0x73,0x20,0x74, - 0x68,0x65,0x20,0x74,0x69,0x6d,0x65,0x20, - 0x66,0x6f,0x72,0x20,0x61,0x6c,0x6c,0x20}; - byte ciphertext[24]; - byte decrypted[24]; - - CBC_Mode::Encryption encryption_DES_CBC; - encryption_DES_CBC.SetKeyWithIV(key, 8, iv); - encryption_DES_CBC.ProcessString(ciphertext, plaintext, 24); - - CBC_Mode::Decryption decryption_DES_CBC; - decryption_DES_CBC.SetKeyWithIV(key, 8, iv); - decryption_DES_CBC.ProcessString(decrypted, ciphertext, 24); - - if (memcmp(plaintext, decrypted, 24) != 0) - { - cerr << "DES-CBC Encryption/decryption failed.\n"; - abort(); - } - cout << "3. DES-CBC Encryption/decryption succeeded.\n"; - - // hash - const byte message[] = {'a', 'b', 'c'}; - const byte expectedDigest[] = {0xA9,0x99,0x3E,0x36,0x47,0x06,0x81,0x6A,0xBA,0x3E,0x25,0x71,0x78,0x50,0xC2,0x6C,0x9C,0xD0,0xD8,0x9D}; - byte digest[20]; - - SHA1 sha; - sha.Update(message, 3); - sha.Final(digest); - - if (memcmp(digest, expectedDigest, 20) != 0) - { - cerr << "SHA-1 hash failed.\n"; - abort(); - } - cout << "4. SHA-1 hash succeeded.\n"; - - // create auto-seeded X9.17 RNG object, if available -#ifdef OS_RNG_AVAILABLE - AutoSeededX917RNG rng; -#else - // this is used to allow this function to compile on platforms that don't have auto-seeded RNGs - RandomNumberGenerator &rng(NullRNG()); -#endif - - // generate DSA key - DSA::PrivateKey dsaPrivateKey; - dsaPrivateKey.GenerateRandomWithKeySize(rng, 1024); - DSA::PublicKey dsaPublicKey; - dsaPublicKey.AssignFrom(dsaPrivateKey); - if (!dsaPrivateKey.Validate(rng, 3) || !dsaPublicKey.Validate(rng, 3)) - { - cerr << "DSA key generation failed.\n"; - abort(); - } - cout << "5. DSA key generation succeeded.\n"; - - // encode DSA key - std::string encodedDsaPublicKey, encodedDsaPrivateKey; - dsaPublicKey.DEREncode(StringSink(encodedDsaPublicKey).Ref()); - dsaPrivateKey.DEREncode(StringSink(encodedDsaPrivateKey).Ref()); - - // decode DSA key - DSA::PrivateKey decodedDsaPrivateKey; - decodedDsaPrivateKey.BERDecode(StringStore(encodedDsaPrivateKey).Ref()); - DSA::PublicKey decodedDsaPublicKey; - decodedDsaPublicKey.BERDecode(StringStore(encodedDsaPublicKey).Ref()); - - if (!decodedDsaPrivateKey.Validate(rng, 3) || !decodedDsaPublicKey.Validate(rng, 3)) - { - cerr << "DSA key encode/decode failed.\n"; - abort(); - } - cout << "6. DSA key encode/decode succeeded.\n"; - - // sign and verify - byte signature[40]; - DSA::Signer signer(dsaPrivateKey); - assert(signer.SignatureLength() == 40); - signer.SignMessage(rng, message, 3, signature); - - DSA::Verifier verifier(dsaPublicKey); - if (!verifier.VerifyMessage(message, 3, signature, 40)) - { - cerr << "DSA signature and verification failed.\n"; - abort(); - } - cout << "7. DSA signature and verification succeeded.\n"; - - - // try to verify an invalid signature - signature[0] ^= 1; - if (verifier.VerifyMessage(message, 3, signature, 40)) - { - cerr << "DSA signature verification failed to detect bad signature.\n"; - abort(); - } - cout << "8. DSA signature verification successfully detected bad signature.\n"; - - // try to use an invalid key length - try - { - encryption_DES_CBC.SetKey(key, 5); - - // should not be here - cerr << "DES implementation did not detect use of invalid key length.\n"; - abort(); - } - catch (InvalidArgument &e) - { - cout << "9. Caught expected exception when using invalid key length. Exception message follows: "; - cout << e.what() << endl; - } - - cout << "\nFIPS 140-2 Sample Application completed normally.\n"; -} - void FIPS140_GenerateRandomFiles() { #ifdef OS_RNG_AVAILABLE @@ -606,6 +453,23 @@ void DigestFile(const char *filename) sha256Filter.TransferTo(encoder); } +void HmacFile(const char *hexKey, const char *file) +{ + member_ptr mac; + if (stricmp(hexKey, "selftest") == 0) + { + cerr << "Computing HMAC/SHA1 value for self test.\n"; + mac.reset(NewIntegrityCheckingMAC()); + } + else + { + std::string decodedKey; + StringSource(hexKey, true, new HexDecoder(new StringSink(decodedKey))); + mac.reset(new HMAC((const byte *)decodedKey.data(), decodedKey.size())); + } + FileSource(file, true, new HashFilter(*mac, new HexEncoder(new FileSink(cout)))); +} + string EncryptString(const char *instr, const char *passPhrase) { string outstr; diff --git a/tiger.cpp b/tiger.cpp index 12519741..50dfb462 100644 --- a/tiger.cpp +++ b/tiger.cpp @@ -8,11 +8,11 @@ NAMESPACE_BEGIN(CryptoPP) -void Tiger::Init() +void Tiger::InitState(HashWordType *state) { - m_digest[0] = W64LIT(0x0123456789ABCDEF); - m_digest[1] = W64LIT(0xFEDCBA9876543210); - m_digest[2] = W64LIT(0xF096A5B4C3B2E187); + state[0] = W64LIT(0x0123456789ABCDEF); + state[1] = W64LIT(0xFEDCBA9876543210); + state[2] = W64LIT(0xF096A5B4C3B2E187); } void Tiger::TruncatedFinal(byte *hash, unsigned int size) diff --git a/tiger.h b/tiger.h index 31b5ee67..9f0f83a6 100644 --- a/tiger.h +++ b/tiger.h @@ -10,18 +10,15 @@ NAMESPACE_BEGIN(CryptoPP) /// Tiger -class Tiger : public IteratedHashWithStaticTransform +class Tiger : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 24}; - Tiger() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word64 *digest, const word64 *data); void TruncatedFinal(byte *hash, unsigned int size); static const char * StaticAlgorithmName() {return "Tiger";} protected: - void Init(); - static const word64 table[4*256]; }; diff --git a/trdlocal.cpp b/trdlocal.cpp index f810c14c..e96c685a 100644 --- a/trdlocal.cpp +++ b/trdlocal.cpp @@ -1,7 +1,11 @@ // trdlocal.cpp - written and placed in the public domain by Wei Dai #include "pch.h" + +#ifndef CRYPTOPP_IMPORTS + #include "trdlocal.h" +#include #ifdef THREADS_AVAILABLE @@ -64,3 +68,5 @@ void *ThreadLocalStorage::GetValue() const NAMESPACE_END #endif // #ifdef THREADS_AVAILABLE + +#endif diff --git a/trdlocal.h b/trdlocal.h index f07b7937..92d244a0 100644 --- a/trdlocal.h +++ b/trdlocal.h @@ -8,8 +8,7 @@ #include "misc.h" #ifdef HAS_WINTHREADS -#include -typedef DWORD ThreadLocalIndexType; +typedef unsigned long ThreadLocalIndexType; #else #include typedef pthread_key_t ThreadLocalIndexType; @@ -18,7 +17,7 @@ typedef pthread_key_t ThreadLocalIndexType; NAMESPACE_BEGIN(CryptoPP) //! thread local storage -class ThreadLocalStorage : public NotCopyable +class CRYPTOPP_DLL ThreadLocalStorage : public NotCopyable { public: //! exception thrown by ThreadLocalStorage class diff --git a/ttmac.h b/ttmac.h index 7b9a85af..9065b65d 100644 --- a/ttmac.h +++ b/ttmac.h @@ -16,7 +16,7 @@ public: static std::string StaticAlgorithmName() {return std::string("Two-Track-MAC");} enum {DIGESTSIZE=20}; - TTMAC_Base() : IteratedHash(DIGESTSIZE*2) {} + TTMAC_Base() {SetStateSize(DIGESTSIZE*2);} unsigned int DigestSize() const {return DIGESTSIZE;}; void UncheckedSetKey(const byte *userKey, unsigned int keylength); @@ -24,14 +24,14 @@ public: protected: static void Transform (word32 *digest, const word32 *X, bool last); - void vTransform(const word32 *data) {Transform(m_digest, data, false);} + void HashEndianCorrectedBlock(const word32 *data) {Transform(m_digest, data, false);} void Init(); FixedSizeSecBlock m_key; }; //! Two-Track-MAC -typedef MessageAuthenticationCodeTemplate TTMAC; +typedef MessageAuthenticationCodeFinal TTMAC; NAMESPACE_END diff --git a/twofish.h b/twofish.h index d1edfb7c..cd2c2a68 100644 --- a/twofish.h +++ b/twofish.h @@ -17,7 +17,7 @@ struct Twofish_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 0, /// Twofish class Twofish : public Twofish_Info, public BlockCipherDocumentation { - class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate + class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl { public: void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); @@ -46,8 +46,8 @@ class Twofish : public Twofish_Info, public BlockCipherDocumentation }; public: - typedef BlockCipherTemplate Encryption; - typedef BlockCipherTemplate Decryption; + typedef BlockCipherFinal Encryption; + typedef BlockCipherFinal Decryption; }; typedef Twofish::Encryption TwofishEncryption; diff --git a/wake.h b/wake.h index 230dfc6e..d6b15765 100644 --- a/wake.h +++ b/wake.h @@ -43,15 +43,15 @@ protected: template struct WAKE_CFB : public WAKE_Info, public SymmetricCipherDocumentation { - typedef SymmetricCipherFinalTemplate, CFB_EncryptionTemplate<> > > Encryption; - typedef SymmetricCipherFinalTemplate, CFB_DecryptionTemplate<> > > Decryption; + typedef SymmetricCipherFinal, CFB_EncryptionTemplate<> > > Encryption; + typedef SymmetricCipherFinal, CFB_DecryptionTemplate<> > > Decryption; }; //! WAKE-OFB template struct WAKE_OFB : public WAKE_Info, public SymmetricCipherDocumentation { - typedef SymmetricCipherFinalTemplate, AdditiveCipherTemplate<> > > Encryption; + typedef SymmetricCipherFinal, AdditiveCipherTemplate<> > > Encryption; typedef Encryption Decryption; }; diff --git a/whrlpool.cpp b/whrlpool.cpp index e9207e67..f2462f2c 100644 --- a/whrlpool.cpp +++ b/whrlpool.cpp @@ -62,10 +62,10 @@ void Whirlpool_TestInstantiations() Whirlpool x; } -void Whirlpool::Init() +void Whirlpool::InitState(HashWordType *state) { - m_digest[0] = m_digest[1] = m_digest[2] = m_digest[3] = - m_digest[4] = m_digest[5] = m_digest[6] = m_digest[7] = 0; + state[0] = state[1] = state[2] = state[3] = + state[4] = state[5] = state[6] = state[7] = 0; } void Whirlpool::TruncatedFinal(byte *hash, unsigned int size) diff --git a/whrlpool.h b/whrlpool.h index 4e3911d2..fbec1b64 100644 --- a/whrlpool.h +++ b/whrlpool.h @@ -11,17 +11,13 @@ NAMESPACE_BEGIN(CryptoPP) //! Whirlpool /*! 512 Bit Hash */ -class Whirlpool : public IteratedHashWithStaticTransform +class Whirlpool : public IteratedHashWithStaticTransform { public: - enum {DIGESTSIZE = 64}; - Whirlpool() : IteratedHashWithStaticTransform(DIGESTSIZE) {Init();} + static void InitState(HashWordType *state); static void Transform(word64 *digest, const word64 *data); void TruncatedFinal(byte *hash, unsigned int size); static const char * StaticAlgorithmName() {return "Whirlpool";} - -protected: - void Init(); }; NAMESPACE_END diff --git a/xormac.h b/xormac.h index 6b5f1892..3e555c28 100644 --- a/xormac.h +++ b/xormac.h @@ -20,7 +20,7 @@ public: enum {DIGESTSIZE = 4+T::DIGESTSIZE}; typedef typename T::HashWordType HashWordType; - XMACC_Base() : IteratedHash(T::DIGESTSIZE) {} + XMACC_Base() {SetStateSize(T::DIGESTSIZE);} void CheckedSetKey(void *, Empty empty, const byte *key, unsigned int length, const NameValuePairs ¶ms); void Resynchronize(const byte *IV) @@ -47,7 +47,7 @@ private: void Init(); static void WriteWord32(byte *output, word32 value); static void XorDigest(HashWordType *digest, const HashWordType *buffer); - void vTransform(const HashWordType *data); + void HashEndianCorrectedBlock(const HashWordType *data); FixedSizeSecBlock::RESULT> m_key; enum {BUFFER_SIZE = ((T::DIGESTSIZE) / sizeof(HashWordType))}; // VC60 workaround @@ -61,7 +61,7 @@ private: and reinitialize it the next time you create an XMACC with the same key. Start counter at 0 when using a key for the first time. */ template -class XMACC : public MessageAuthenticationCodeTemplate > +class XMACC : public ClonableImpl, MessageAuthenticationCodeImpl > > { public: XMACC() {} @@ -102,7 +102,7 @@ template inline void XMACC_Base::XorDigest(HashWordType *digest, co digest[i] ^= buffer[i]; } -template void XMACC_Base::vTransform(const HashWordType *input) +template void XMACC_Base::HashEndianCorrectedBlock(const HashWordType *input) { memcpy(m_buffer, m_key, KEYLENGTH); WriteWord32((byte *)m_buffer.begin()+KEYLENGTH, ++m_index); @@ -123,7 +123,7 @@ template void XMACC_Base::TruncatedFinal(byte *mac, unsigned int si CorrectEndianess(m_data, m_data, BLOCKSIZE - 2*sizeof(HashWordType)); m_data[m_data.size()-2] = ByteReverse(GetBitCountHi()); // byteReverse for backwards compatibility m_data[m_data.size()-1] = ByteReverse(GetBitCountLo()); - vTransform(m_data); + HashEndianCorrectedBlock(m_data); memcpy(m_buffer, m_key, KEYLENGTH); WriteWord32((byte *)m_buffer.begin()+KEYLENGTH, 0); @@ -149,7 +149,7 @@ template bool XMACC_Base::TruncatedVerify(const byte *mac, unsigned CorrectEndianess(m_data, m_data, BLOCKSIZE - 2*sizeof(HashWordType)); m_data[m_data.size()-2] = ByteReverse(GetBitCountHi()); // byteReverse for backwards compatibility m_data[m_data.size()-1] = ByteReverse(GetBitCountLo()); - vTransform(m_data); + HashEndianCorrectedBlock(m_data); memcpy(m_buffer, m_key, KEYLENGTH); WriteWord32((byte *)m_buffer.begin()+KEYLENGTH, 0);