create DLL version, fix GetNextIV() bug in CTR and OFB modes

pull/2/head
weidai 2003-07-04 00:17:37 +00:00
parent e43f746047
commit f278895908
144 changed files with 2680 additions and 1235 deletions

6
3way.h
View File

@ -17,7 +17,7 @@ struct ThreeWay_Info : public FixedBlockSize<12>, public FixedKeyLength<12>, pub
/// <a href="http://www.weidai.com/scan-mirror/cs.html#3-Way">3-Way</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#3-Way">3-Way</a>
class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<ThreeWay_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<ThreeWay_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *key, unsigned int length, unsigned int rounds); 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: public:
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
typedef ThreeWay::Encryption ThreeWayEncryption; typedef ThreeWay::Encryption ThreeWayEncryption;

View File

@ -1,5 +1,5 @@
Crypto++: a C++ Class Library of Cryptographic Primitives Crypto++: a C++ Class Library of Cryptographic Primitives
Version 5.1 3/20/2003 Version 5.0 9/11/2002
This library includes: This library includes:
@ -238,9 +238,15 @@ History
- fixed a bug in HMAC::TruncatedFinal() - fixed a bug in HMAC::TruncatedFinal()
- fixed SKIPJACK byte ordering following NIST clarification dated 5/9/02 - fixed SKIPJACK byte ordering following NIST clarification dated 5/9/02
5.01 (special FIPS 140-2 release, in development) 5.01 - added known answer test for X9.17 RNG in FIPS 140 power-up self test
- added known answer test for X9.17 RNG in FIPS 140 power-up self test - submitted to NIST/CSE, but not publicly released
- is being evaluated for FIPS 140-2 compliance
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 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 - added blinding for RSA and Rabin to defend against timing attacks
@ -253,3 +259,5 @@ History
signature scheme (these fixes are not backwards compatible) signature scheme (these fixes are not backwards compatible)
- fixed a number of compiler warnings, minor bugs, and portability problems - fixed a number of compiler warnings, minor bugs, and portability problems
- removed Sapphire - removed Sapphire
5.2 - Merged in changes for 5.01 - 5.03

2
aes.h
View File

@ -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 #ifdef CRYPTOPP_DOXYGEN_PROCESSING // Use inheritance instead of typedef to get a seperate API reference page for AES
//! AES //! AES
class AES : public Rijndael, public BlockCipherDocumentation {}; class AES : public Rijndael {};
#else #else
typedef Rijndael AES; typedef Rijndael AES;
#endif #endif

View File

@ -207,6 +207,9 @@ public:
void DivisionAlgorithm(Element &r, Element &q, const Element &a, const Element &d) const void DivisionAlgorithm(Element &r, Element &q, const Element &a, const Element &d) const
{Element::Divide(r, q, a, d);} {Element::Divide(r, q, a, d);}
bool operator==(const EuclideanDomainOf<T> &rhs) const
{return true;}
private: private:
mutable Element result; mutable Element result;
}; };
@ -265,6 +268,9 @@ public:
const Element& MultiplicativeInverse(const Element &a) const; const Element& MultiplicativeInverse(const Element &a) const;
bool operator==(const QuotientRing<T> &rhs) const
{return m_domain == rhs.m_domain && m_modulus == rhs.m_modulus;}
protected: protected:
EuclideanDomain m_domain; EuclideanDomain m_domain;
Element m_modulus; Element m_modulus;

View File

@ -1,6 +1,9 @@
// algparam.cpp - written and placed in the public domain by Wei Dai // algparam.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "algparam.h" #include "algparam.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -8,3 +11,5 @@ NAMESPACE_BEGIN(CryptoPP)
bool (*AssignIntToInteger)(const std::type_info &valueType, void *pInteger, const void *pInt) = NULL; bool (*AssignIntToInteger)(const std::type_info &valueType, void *pInteger, const void *pInt) = NULL;
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -243,9 +243,9 @@ AssignFromHelperClass<T, T> AssignFromHelper(T *pObject, const NameValuePairs &s
// ******************************************************** // ********************************************************
// This should allow the linker to discard Integer code if not needed. // 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 BASE, class T> template <class BASE, class T>
class AlgorithmParameters : public NameValuePairs class AlgorithmParameters : public NameValuePairs

12
arc4.h
View File

@ -23,8 +23,8 @@ public:
bool IsSelfInverting() const {return true;} bool IsSelfInverting() const {return true;}
bool IsForwardTransformation() const {return true;} bool IsForwardTransformation() const {return true;}
typedef SymmetricCipherFinalTemplate<ARC4_Base> Encryption; typedef SymmetricCipherFinal<ARC4_Base> Encryption;
typedef SymmetricCipherFinalTemplate<ARC4_Base> Decryption; typedef SymmetricCipherFinal<ARC4_Base> Decryption;
protected: protected:
void UncheckedSetKey(const NameValuePairs &params, const byte *key, unsigned int length, const byte *iv); void UncheckedSetKey(const NameValuePairs &params, const byte *key, unsigned int length, const byte *iv);
@ -35,7 +35,7 @@ protected:
}; };
//! . //! .
typedef SymmetricCipherFinalTemplate<ARC4_Base> ARC4; typedef SymmetricCipherFinal<ARC4_Base> ARC4;
//! Modified ARC4: it discards the first 256 bytes of keystream which may be weaker than the rest //! 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. */ /*! Use #MARC4 typedef rather than this class directly. */
@ -44,15 +44,15 @@ class CRYPTOPP_NO_VTABLE MARC4_Base : public ARC4_Base
public: public:
static const char *StaticAlgorithmName() {return "MARC4";} static const char *StaticAlgorithmName() {return "MARC4";}
typedef SymmetricCipherFinalTemplate<MARC4_Base> Encryption; typedef SymmetricCipherFinal<MARC4_Base> Encryption;
typedef SymmetricCipherFinalTemplate<MARC4_Base> Decryption; typedef SymmetricCipherFinal<MARC4_Base> Decryption;
protected: protected:
unsigned int GetDefaultDiscardBytes() const {return 256;} unsigned int GetDefaultDiscardBytes() const {return 256;}
}; };
//! . //! .
typedef SymmetricCipherFinalTemplate<MARC4_Base> MARC4; typedef SymmetricCipherFinal<MARC4_Base> MARC4;
NAMESPACE_END NAMESPACE_END

View File

@ -1,6 +1,9 @@
// asn.cpp - written and placed in the public domain by Wei Dai // asn.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "asn.h" #include "asn.h"
#include <iomanip> #include <iomanip>
@ -554,3 +557,5 @@ void PKCS8PrivateKey::DEREncode(BufferedTransformation &bt) const
} }
NAMESPACE_END NAMESPACE_END
#endif

46
asn.h
View File

@ -48,7 +48,7 @@ enum ASNIdFlag
inline void BERDecodeError() {throw BERDecodeErr();} inline void BERDecodeError() {throw BERDecodeErr();}
class UnknownOID : public BERDecodeErr class CRYPTOPP_DLL UnknownOID : public BERDecodeErr
{ {
public: public:
UnknownOID() : BERDecodeErr("BER decode error: unknown object identifier") {} 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(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 // 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); CRYPTOPP_DLL void DEREncodeNull(BufferedTransformation &out);
void BERDecodeNull(BufferedTransformation &in); CRYPTOPP_DLL void BERDecodeNull(BufferedTransformation &in);
unsigned int DEREncodeOctetString(BufferedTransformation &out, const byte *str, unsigned int strLen); CRYPTOPP_DLL unsigned int DEREncodeOctetString(BufferedTransformation &out, const byte *str, unsigned int strLen);
unsigned int DEREncodeOctetString(BufferedTransformation &out, const SecByteBlock &str); CRYPTOPP_DLL unsigned int DEREncodeOctetString(BufferedTransformation &out, const SecByteBlock &str);
unsigned int BERDecodeOctetString(BufferedTransformation &in, SecByteBlock &str); CRYPTOPP_DLL unsigned int BERDecodeOctetString(BufferedTransformation &in, SecByteBlock &str);
unsigned int BERDecodeOctetString(BufferedTransformation &in, BufferedTransformation &str); CRYPTOPP_DLL unsigned int BERDecodeOctetString(BufferedTransformation &in, BufferedTransformation &str);
// for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING // for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
unsigned int DEREncodeTextString(BufferedTransformation &out, const std::string &str, byte asnTag); CRYPTOPP_DLL 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 BERDecodeTextString(BufferedTransformation &in, std::string &str, byte asnTag);
unsigned int DEREncodeBitString(BufferedTransformation &out, const byte *str, unsigned int strLen, unsigned int unusedBits=0); CRYPTOPP_DLL 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 BERDecodeBitString(BufferedTransformation &in, SecByteBlock &str, unsigned int &unusedBits);
//! Object Identifier //! Object Identifier
class OID class CRYPTOPP_DLL OID
{ {
public: public:
OID() {} OID() {}
@ -122,7 +122,7 @@ private:
}; };
//! BER General Decoder //! BER General Decoder
class BERGeneralDecoder : public Store class CRYPTOPP_DLL BERGeneralDecoder : public Store
{ {
public: public:
explicit BERGeneralDecoder(BufferedTransformation &inQueue, byte asnTag); explicit BERGeneralDecoder(BufferedTransformation &inQueue, byte asnTag);
@ -152,7 +152,7 @@ private:
}; };
//! DER General Encoder //! DER General Encoder
class DERGeneralEncoder : public ByteQueue class CRYPTOPP_DLL DERGeneralEncoder : public ByteQueue
{ {
public: public:
explicit DERGeneralEncoder(BufferedTransformation &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED); explicit DERGeneralEncoder(BufferedTransformation &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED);
@ -170,7 +170,7 @@ private:
}; };
//! BER Sequence Decoder //! BER Sequence Decoder
class BERSequenceDecoder : public BERGeneralDecoder class CRYPTOPP_DLL BERSequenceDecoder : public BERGeneralDecoder
{ {
public: public:
explicit BERSequenceDecoder(BufferedTransformation &inQueue, byte asnTag = SEQUENCE | CONSTRUCTED) explicit BERSequenceDecoder(BufferedTransformation &inQueue, byte asnTag = SEQUENCE | CONSTRUCTED)
@ -180,7 +180,7 @@ public:
}; };
//! DER Sequence Encoder //! DER Sequence Encoder
class DERSequenceEncoder : public DERGeneralEncoder class CRYPTOPP_DLL DERSequenceEncoder : public DERGeneralEncoder
{ {
public: public:
explicit DERSequenceEncoder(BufferedTransformation &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED) explicit DERSequenceEncoder(BufferedTransformation &outQueue, byte asnTag = SEQUENCE | CONSTRUCTED)
@ -190,7 +190,7 @@ public:
}; };
//! BER Set Decoder //! BER Set Decoder
class BERSetDecoder : public BERGeneralDecoder class CRYPTOPP_DLL BERSetDecoder : public BERGeneralDecoder
{ {
public: public:
explicit BERSetDecoder(BufferedTransformation &inQueue, byte asnTag = SET | CONSTRUCTED) explicit BERSetDecoder(BufferedTransformation &inQueue, byte asnTag = SET | CONSTRUCTED)
@ -200,7 +200,7 @@ public:
}; };
//! DER Set Encoder //! DER Set Encoder
class DERSetEncoder : public DERGeneralEncoder class CRYPTOPP_DLL DERSetEncoder : public DERGeneralEncoder
{ {
public: public:
explicit DERSetEncoder(BufferedTransformation &outQueue, byte asnTag = SET | CONSTRUCTED) explicit DERSetEncoder(BufferedTransformation &outQueue, byte asnTag = SET | CONSTRUCTED)
@ -227,7 +227,7 @@ public:
}; };
//! . //! .
class ASN1Key : public ASN1CryptoMaterial class CRYPTOPP_DLL ASN1Key : public ASN1CryptoMaterial
{ {
public: public:
virtual OID GetAlgorithmID() const =0; virtual OID GetAlgorithmID() const =0;
@ -245,7 +245,7 @@ public:
}; };
//! encodes/decodes subjectPublicKeyInfo //! encodes/decodes subjectPublicKeyInfo
class X509PublicKey : virtual public ASN1Key, public PublicKey class CRYPTOPP_DLL X509PublicKey : virtual public ASN1Key, public PublicKey
{ {
public: public:
void BERDecode(BufferedTransformation &bt); void BERDecode(BufferedTransformation &bt);
@ -253,7 +253,7 @@ public:
}; };
//! encodes/decodes privateKeyInfo //! encodes/decodes privateKeyInfo
class PKCS8PrivateKey : virtual public ASN1Key, public PrivateKey class CRYPTOPP_DLL PKCS8PrivateKey : virtual public ASN1Key, public PrivateKey
{ {
public: public:
void BERDecode(BufferedTransformation &bt); void BERDecode(BufferedTransformation &bt);

View File

@ -1,6 +1,9 @@
// basecode.cpp - written and placed in the public domain by Wei Dai // basecode.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "basecode.h" #include "basecode.h"
#include "fltrimpl.h" #include "fltrimpl.h"
#include <ctype.h> #include <ctype.h>
@ -229,3 +232,5 @@ unsigned int Grouper::Put2(const byte *begin, unsigned int length, int messageEn
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -6,7 +6,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
class BaseN_Encoder : public Unflushable<Filter> class CRYPTOPP_DLL BaseN_Encoder : public Unflushable<Filter>
{ {
public: public:
BaseN_Encoder(BufferedTransformation *attachment=NULL) BaseN_Encoder(BufferedTransformation *attachment=NULL)
@ -31,7 +31,7 @@ private:
SecByteBlock m_outBuf; SecByteBlock m_outBuf;
}; };
class BaseN_Decoder : public Unflushable<Filter> class CRYPTOPP_DLL BaseN_Decoder : public Unflushable<Filter>
{ {
public: public:
BaseN_Decoder(BufferedTransformation *attachment=NULL) BaseN_Decoder(BufferedTransformation *attachment=NULL)
@ -55,7 +55,7 @@ private:
SecByteBlock m_outBuf; SecByteBlock m_outBuf;
}; };
class Grouper : public Bufferless<Filter> class CRYPTOPP_DLL Grouper : public Bufferless<Filter>
{ {
public: public:
Grouper(BufferedTransformation *attachment=NULL) Grouper(BufferedTransformation *attachment=NULL)

View File

@ -16,7 +16,7 @@ struct Blowfish_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 1,
//! <a href="http://www.weidai.com/scan-mirror/cs.html#Blowfish">Blowfish</a> //! <a href="http://www.weidai.com/scan-mirror/cs.html#Blowfish">Blowfish</a>
class Blowfish : public Blowfish_Info, public BlockCipherDocumentation class Blowfish : public Blowfish_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<Blowfish_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Blowfish_Info>
{ {
public: public:
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
@ -33,8 +33,8 @@ class Blowfish : public Blowfish_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
typedef Blowfish::Encryption BlowfishEncryption; typedef Blowfish::Encryption BlowfishEncryption;

View File

@ -21,7 +21,7 @@ struct Camellia_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 1
/// <a href="http://www.weidai.com/scan-mirror/cs.html#Camellia">Camellia</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#Camellia">Camellia</a>
class Camellia : public Camellia_Info, public BlockCipherDocumentation class Camellia : public Camellia_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<Camellia_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Camellia_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int keylen); void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int keylen);
@ -41,8 +41,8 @@ class Camellia : public Camellia_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
typedef Camellia::Encryption CamelliaEncryption; typedef Camellia::Encryption CamelliaEncryption;

12
cast.h
View File

@ -24,7 +24,7 @@ struct CAST128_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 5,
/// <a href="http://www.weidai.com/scan-mirror/cs.html#CAST-128">CAST-128</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#CAST-128">CAST-128</a>
class CAST128 : public CAST128_Info, public BlockCipherDocumentation class CAST128 : public CAST128_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherBaseTemplate<CAST128_Info> class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST128_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length);
@ -47,8 +47,8 @@ class CAST128 : public CAST128_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
//! . //! .
@ -60,7 +60,7 @@ struct CAST256_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16
//! <a href="http://www.weidai.com/scan-mirror/cs.html#CAST-256">CAST-256</a> //! <a href="http://www.weidai.com/scan-mirror/cs.html#CAST-256">CAST-256</a>
class CAST256 : public CAST256_Info, public BlockCipherDocumentation class CAST256 : public CAST256_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherBaseTemplate<CAST256_Info> class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST256_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length = 8); void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length = 8);
@ -76,8 +76,8 @@ class CAST256 : public CAST256_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
typedef CAST128::Encryption CAST128Encryption; typedef CAST128::Encryption CAST128Encryption;

63
cbcmac.cpp Normal file
View File

@ -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 &params)
{
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

View File

@ -6,22 +6,21 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
template <class T> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_MAC_Base : public MessageAuthenticationCode
class CRYPTOPP_NO_VTABLE CBC_MAC_Base : public SameKeyLengthAs<T>, public MessageAuthenticationCode
{ {
public: public:
static std::string StaticAlgorithmName() {return std::string("CBC-MAC(") + T::StaticAlgorithmName() + ")";}
CBC_MAC_Base() {} CBC_MAC_Base() {}
void CheckedSetKey(void *, Empty empty, const byte *key, unsigned int length, const NameValuePairs &params); void CheckedSetKey(void *, Empty empty, const byte *key, unsigned int length, const NameValuePairs &params);
void Update(const byte *input, unsigned int length); void Update(const byte *input, unsigned int length);
void TruncatedFinal(byte *mac, unsigned int size); void TruncatedFinal(byte *mac, unsigned int size);
unsigned int DigestSize() const {return m_cipher.BlockSize();} unsigned int DigestSize() const {return const_cast<CBC_MAC_Base*>(this)->AccessCipher().BlockSize();}
protected:
virtual BlockCipher & AccessCipher() =0;
private: private:
void ProcessBuf(); void ProcessBuf();
typename T::Encryption m_cipher;
SecByteBlock m_reg; SecByteBlock m_reg;
unsigned int m_counter; unsigned int m_counter;
}; };
@ -32,68 +31,20 @@ private:
messages use DMAC. messages use DMAC.
*/ */
template <class T> template <class T>
class CBC_MAC : public MessageAuthenticationCodeTemplate<CBC_MAC_Base<T> > class CBC_MAC : public MessageAuthenticationCodeImpl<CBC_MAC_Base, CBC_MAC<T> >, public SameKeyLengthAs<T>
{ {
public: public:
CBC_MAC() {} CBC_MAC() {}
CBC_MAC(const byte *key, unsigned int length=CBC_MAC_Base<T>::DEFAULT_KEYLENGTH) CBC_MAC(const byte *key, unsigned int length=DEFAULT_KEYLENGTH)
{SetKey(key, length);} {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 <class T>
void CBC_MAC_Base<T>::CheckedSetKey(void *, Empty empty, const byte *key, unsigned int length, const NameValuePairs &params)
{
m_cipher.SetKey(key, length, params);
m_reg.CleanNew(m_cipher.BlockSize());
m_counter = 0;
}
template <class T>
void CBC_MAC_Base<T>::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 <class T>
void CBC_MAC_Base<T>::TruncatedFinal(byte *mac, unsigned int size)
{
ThrowIfInvalidTruncatedSize(size);
if (m_counter)
ProcessBuf();
memcpy(mac, m_reg, size);
memset(m_reg, 0, T::BLOCKSIZE);
}
template <class T>
void CBC_MAC_Base<T>::ProcessBuf()
{
m_cipher.ProcessBlock(m_reg);
m_counter = 0;
}
NAMESPACE_END NAMESPACE_END
#endif #endif

View File

@ -1,6 +1,9 @@
// channels.cpp - written and placed in the public domain by Wei Dai // channels.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "channels.h" #include "channels.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -151,7 +154,7 @@ unsigned int ChannelSwitch::ChannelPut2(const std::string &channel, const byte *
while (!m_it.End()) while (!m_it.End())
{ {
WasBlocked: WasBlocked:
if (m_it.Destination().ChannelPut2(m_it.Channel(), begin, length, messageEnd, blocking)) if (m_it.Destination().ChannelPut2(m_it.Channel(), begin, length, messageEnd, blocking))
{ {
m_blocked = true; m_blocked = true;
@ -311,3 +314,5 @@ void ChannelSwitch::RemoveRoute(const std::string &inChannel, BufferedTransforma
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -77,7 +77,7 @@ public:
}; };
//! Route input to different and/or multiple channels based on channel ID //! Route input to different and/or multiple channels based on channel ID
class ChannelSwitch : public Multichannel<Sink>, public ChannelSwitchTypedefs class CRYPTOPP_DLL ChannelSwitch : public Multichannel<Sink>, public ChannelSwitchTypedefs
{ {
public: public:
ChannelSwitch() : m_it(*this), m_blocked(false) {} ChannelSwitch() : m_it(*this), m_blocked(false) {}

View File

@ -100,11 +100,7 @@ typedef unsigned char byte; // moved outside namespace for Borland C++Builde
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
typedef unsigned short word16; typedef unsigned short word16;
#if defined(__alpha) && !defined(_MSC_VER)
typedef unsigned int word32; typedef unsigned int word32;
#else
typedef unsigned long word32;
#endif
#if defined(__GNUC__) || defined(__MWERKS__) #if defined(__GNUC__) || defined(__MWERKS__)
# define WORD64_AVAILABLE # define WORD64_AVAILABLE
@ -184,14 +180,46 @@ NAMESPACE_END
#endif #endif
#ifdef _MSC_VER #ifdef _MSC_VER
// 4231: nonstandard extension used : 'extern' before template explicit instantiation
// 4250: dominance // 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 // 4660: explicitly instantiating a class that's already implicitly instantiated
// 4661: no suitable definition provided for explicit template instantiation request // 4661: no suitable definition provided for explicit template instantiation request
// 4786: identifer was truncated in debug information // 4786: identifer was truncated in debug information
// 4355: 'this' : used in base member initializer list // 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 #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 ******************** // ***************** determine availability of OS features ********************
#ifndef NO_OS_DEPENDENCE #ifndef NO_OS_DEPENDENCE

545
cryptdll.dsp Normal file
View File

@ -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

View File

@ -25,8 +25,8 @@ CFG=cryptest - Win32 Debug
# Begin Project # Begin Project
# PROP AllowPerConfigDependencies 0 # PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName "" # PROP Scc_ProjName "Perforce Project"
# PROP Scc_LocalPath "" # PROP Scc_LocalPath "."
CPP=cl.exe CPP=cl.exe
RSC=rc.exe RSC=rc.exe
@ -45,7 +45,7 @@ RSC=rc.exe
# PROP Ignore_Export_Lib 0 # PROP Ignore_Export_Lib 0
# PROP Target_Dir "" # 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 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 BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe BSC32=bscmake.exe
@ -53,11 +53,11 @@ BSC32=bscmake.exe
# ADD BSC32 /nologo # ADD BSC32 /nologo
LINK32=link.exe 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 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 # 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 # SUBTRACT LINK32 /pdb:none /incremental:yes
# Begin Special Build Tool # Begin Special Build Tool
SOURCE="$(InputPath)" 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 # End Special Build Tool
!ELSEIF "$(CFG)" == "cryptest - Win32 FIPS 140 Debug" !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 Ignore_Export_Lib 0
# PROP Target_Dir "" # 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 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 BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe BSC32=bscmake.exe
@ -83,10 +83,10 @@ BSC32=bscmake.exe
# ADD BSC32 /nologo # ADD BSC32 /nologo
LINK32=link.exe 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 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 # Begin Special Build Tool
SOURCE="$(InputPath)" 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 # End Special Build Tool
!ELSEIF "$(CFG)" == "cryptest - Win32 Release" !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 Ignore_Export_Lib 0
# PROP Target_Dir "" # PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c # 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 BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG"
BSC32=bscmake.exe BSC32=bscmake.exe
@ -128,7 +128,7 @@ LINK32=link.exe
# PROP Ignore_Export_Lib 0 # PROP Ignore_Export_Lib 0
# PROP Target_Dir "" # PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c # 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 BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG"
BSC32=bscmake.exe BSC32=bscmake.exe
@ -392,6 +392,10 @@ SOURCE=.\datatest.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\dlltest.cpp
# End Source File
# Begin Source File
SOURCE=.\factory.h SOURCE=.\factory.h
# End Source File # End Source File
# Begin Source File # Begin Source File

View File

@ -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> Project: "cryptest"=.\cryptest.dsp - Package Owner=<4>
Package=<5> Package=<5>
{{{ {{{
begin source code control
Perforce Project
.
end source code control
}}} }}}
Package=<4> Package=<4>
@ -22,6 +45,10 @@ Project: "cryptlib"=.\cryptlib.dsp - Package Owner=<4>
Package=<5> Package=<5>
{{{ {{{
begin source code control
Perforce Project
.
end source code control
}}} }}}
Package=<4> 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: Global:
Package=<5> Package=<5>

View File

@ -1,6 +1,9 @@
// cryptlib.cpp - written and placed in the public domain by Wei Dai // cryptlib.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "cryptlib.h" #include "cryptlib.h"
#include "misc.h" #include "misc.h"
#include "filters.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."); throw SelfTestFailure("Cryptographic algorithms are disabled before the power-up self tests are performed.");
if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_FAILED) 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 NAMESPACE_END
#endif

View File

@ -25,8 +25,8 @@ CFG=cryptlib - Win32 Debug
# Begin Project # Begin Project
# PROP AllowPerConfigDependencies 0 # PROP AllowPerConfigDependencies 0
# PROP Scc_ProjName "" # PROP Scc_ProjName "Perforce Project"
# PROP Scc_LocalPath "" # PROP Scc_LocalPath "."
CPP=cl.exe CPP=cl.exe
RSC=rc.exe RSC=rc.exe
@ -43,7 +43,7 @@ RSC=rc.exe
# PROP Intermediate_Dir "FIPS_140_Release" # PROP Intermediate_Dir "FIPS_140_Release"
# PROP Target_Dir "" # 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 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 BASE RSC /l 0x409
# ADD RSC /l 0x409 # ADD RSC /l 0x409
BSC32=bscmake.exe BSC32=bscmake.exe
@ -51,7 +51,7 @@ BSC32=bscmake.exe
# ADD BSC32 /nologo # ADD BSC32 /nologo
LIB32=link.exe -lib LIB32=link.exe -lib
# ADD BASE LIB32 /nologo # ADD BASE LIB32 /nologo
# ADD LIB32 /nologo /out:"FIPS_140_Release\cryptopp.lib" # ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "cryptlib - Win32 FIPS 140 Debug" !ELSEIF "$(CFG)" == "cryptlib - Win32 FIPS 140 Debug"
@ -66,7 +66,7 @@ LIB32=link.exe -lib
# PROP Intermediate_Dir "FIPS_140_Debug" # PROP Intermediate_Dir "FIPS_140_Debug"
# PROP Target_Dir "" # 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 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 BASE RSC /l 0x409
# ADD RSC /l 0x409 # ADD RSC /l 0x409
BSC32=bscmake.exe BSC32=bscmake.exe
@ -74,7 +74,7 @@ BSC32=bscmake.exe
# ADD BSC32 /nologo # ADD BSC32 /nologo
LIB32=link.exe -lib LIB32=link.exe -lib
# ADD BASE LIB32 /nologo # ADD BASE LIB32 /nologo
# ADD LIB32 /nologo /out:"FIPS_140_Debug\cryptopp.lib" # ADD LIB32 /nologo
!ELSEIF "$(CFG)" == "cryptlib - Win32 Release" !ELSEIF "$(CFG)" == "cryptlib - Win32 Release"
@ -89,7 +89,7 @@ LIB32=link.exe -lib
# PROP Intermediate_Dir "Release" # PROP Intermediate_Dir "Release"
# PROP Target_Dir "" # PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /FD /c # 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 BASE RSC /l 0x409
# ADD RSC /l 0x409 # ADD RSC /l 0x409
BSC32=bscmake.exe BSC32=bscmake.exe
@ -112,7 +112,7 @@ LIB32=link.exe -lib
# PROP Intermediate_Dir "Debug" # PROP Intermediate_Dir "Debug"
# PROP Target_Dir "" # PROP Target_Dir ""
# ADD BASE CPP /nologo /W3 /GX /Z7 /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /FD /c # 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 BASE RSC /l 0x409
# ADD RSC /l 0x409 # ADD RSC /l 0x409
BSC32=bscmake.exe BSC32=bscmake.exe
@ -242,6 +242,10 @@ SOURCE=.\casts.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\cbcmac.cpp
# End Source File
# Begin Source File
SOURCE=.\channels.cpp SOURCE=.\channels.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
@ -282,6 +286,11 @@ SOURCE=.\diamondt.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\dll.cpp
# SUBTRACT CPP /YX /Yc /Yu
# End Source File
# Begin Source File
SOURCE=.\dsa.cpp SOURCE=.\dsa.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
@ -358,6 +367,10 @@ SOURCE=.\hex.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File
SOURCE=.\hmac.cpp
# End Source File
# Begin Source File
SOURCE=.\hrtimer.cpp SOURCE=.\hrtimer.cpp
# End Source File # End Source File
# Begin Source File # Begin Source File

View File

@ -4,7 +4,7 @@
classes that provide a uniform interface to this library. classes that provide a uniform interface to this library.
*/ */
/*! \mainpage <a href="http://www.cryptopp.com">Crypto++</a><sup><small>TM</small></sup> Library 5.1 Reference Manual /*! \mainpage <a href="http://www.cryptopp.com">Crypto++</a><sup><small>TM</small></sup> Library 5.2 Reference Manual
<dl> <dl>
<dt>Abstract Base Classes<dd> <dt>Abstract Base Classes<dd>
cryptlib.h cryptlib.h
@ -46,6 +46,26 @@
fips140.h fips140.h
</dl> </dl>
In the FIPS 140-2 validated DLL version of Crypto++, only the following implementation class are available.
<dl>
<dt>Block Ciphers<dd>
AES, DES, DES_EDE2, DES_EDE3, SKIPJACK
<dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
ECB_Mode <BC>, CTR_Mode <BC>, CBC_Mode <BC>, CFB_Mode <BC>, OFB_Mode <BC>
<dt>Hash Functions<dd>
SHA, SHA256, SHA384, SHA512
<dt>Public Key Signature Schemes<dd>
RSASSA <PKCS1v15, SHA>, DSA, ECDSA <ECP, SHA>, ECDSA <EC2N, SHA>
<dt>Message Authentication Codes<dd>
HMAC <SHA>, HMAC <SHA256>, HMAC <SHA384>, HMAC <SHA512>, CBC_MAC <DES>, CBC_MAC <DES_EDE2>, CBC_MAC <DES_EDE3>
<dt>Random Number Generators<dd>
AutoSeededX917RNG <DES_EDE3>
<dt>Key Agreement<dd>
#DH
<dt>Public Key Cryptosystems<dd>
RSAES <OAEP<SHA> >
</dl>
<p>This reference manual is a work in progress. Some classes are still lacking detailed descriptions. <p>This reference manual is a work in progress. Some classes are still lacking detailed descriptions.
<p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual. <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
<p>Thanks to Ryan Phillips for providing the Doxygen configuration file <p>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 #define CRYPTOPP_CRYPTLIB_H
#include "config.h" #include "config.h"
#include <limits.h> #include "stdcpp.h"
#include <exception>
#include <string>
#include <typeinfo>
#include <assert.h>
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -85,7 +101,7 @@ typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian;
typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian; typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian;
//! base class for all exceptions thrown by Crypto++ //! base class for all exceptions thrown by Crypto++
class Exception : public std::exception class CRYPTOPP_DLL Exception : public std::exception
{ {
public: public:
//! error types //! error types
@ -120,42 +136,42 @@ private:
}; };
//! exception thrown when an invalid argument is detected //! exception thrown when an invalid argument is detected
class InvalidArgument : public Exception class CRYPTOPP_DLL InvalidArgument : public Exception
{ {
public: public:
explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {} explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
}; };
//! exception thrown by decryption filters when trying to decrypt an invalid ciphertext //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext
class InvalidDataFormat : public Exception class CRYPTOPP_DLL InvalidDataFormat : public Exception
{ {
public: public:
explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {} explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
}; };
//! exception thrown by decryption filters when trying to decrypt an invalid ciphertext //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext
class InvalidCiphertext : public InvalidDataFormat class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
{ {
public: public:
explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {} explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
}; };
//! exception thrown by a class if a non-implemented method is called //! exception thrown by a class if a non-implemented method is called
class NotImplemented : public Exception class CRYPTOPP_DLL NotImplemented : public Exception
{ {
public: public:
explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {} 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 //! 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: public:
explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {} explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
}; };
//! error reported by the operating system //! error reported by the operating system
class OS_Error : public Exception class CRYPTOPP_DLL OS_Error : public Exception
{ {
public: public:
OS_Error(ErrorType errorType, const std::string s, const std::string& operation, int errorCode) OS_Error(ErrorType errorType, const std::string s, const std::string& operation, int errorCode)
@ -173,7 +189,7 @@ protected:
}; };
//! used to return decoding results //! used to return decoding results
struct DecodingResult struct CRYPTOPP_DLL DecodingResult
{ {
explicit DecodingResult() : isValidCoding(false), messageLength(0) {} explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
explicit DecodingResult(unsigned int len) : isValidCoding(true), messageLength(len) {} explicit DecodingResult(unsigned int len) : isValidCoding(true), messageLength(len) {}
@ -249,21 +265,21 @@ public:
} }
//! get a list of value names that can be retrieved //! 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;} {std::string result; GetValue("ValueNames", result); return result;}
//! get a named value with type int //! get a named value with type int
/*! used to ensure we don't accidentally try to get an unsigned 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) */ 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);} {return GetValue(name, value);}
//! get a named value with type int, with default //! 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);} {return GetValueWithDefault(name, defaultValue);}
//! used by derived classes to check for type mismatch //! 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);} {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
template <class T> template <class T>
@ -273,14 +289,14 @@ public:
throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); 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)) if (!GetIntValue(name, value))
throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
} }
//! to be implemented by derived classes, users should use one of the above functions instead //! 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 //! namespace containing value name definitions
@ -294,19 +310,19 @@ DOCUMENTED_NAMESPACE_BEGIN(Name)
DOCUMENTED_NAMESPACE_END DOCUMENTED_NAMESPACE_END
//! . //! .
class NullNameValuePairs : public NameValuePairs class CRYPTOPP_DLL NullNameValuePairs : public NameValuePairs
{ {
public: public:
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const {return false;} 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 //! 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: public:
virtual ~Clonable() {} virtual ~Clonable() {}
@ -316,7 +332,7 @@ public:
//! interface for all crypto algorithms //! interface for all crypto algorithms
class CRYPTOPP_NO_VTABLE Algorithm : public Clonable class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
{ {
public: public:
/*! When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true, /*! 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 //! keying interface for crypto algorithms that take byte strings as keys
class CRYPTOPP_NO_VTABLE SimpleKeyingInterface class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
{ {
public: public:
//! returns smallest valid key length in bytes */ //! returns smallest valid key length in bytes */
@ -399,7 +415,7 @@ protected:
These classes should not be used directly, but only in combination with These classes should not be used directly, but only in combination with
a mode class (see CipherModeDocumentation in modes.h). 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: public:
//! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock //! 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 //! 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: public:
//! return a reference to this object, //! return a reference to this object,
@ -498,7 +514,7 @@ public:
be hashed in pieces by calling Update() on each piece followed by be hashed in pieces by calling Update() on each piece followed by
calling Final(). calling Final().
*/ */
class CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
{ {
public: public:
//! process more input //! process more input
@ -519,6 +535,9 @@ public:
//! size of the hash returned by Final() //! size of the hash returned by Final()
virtual unsigned int DigestSize() const =0; 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 //! input to Update() should have length a multiple of this for optimal speed
virtual unsigned int OptimalBlockSize() const {return 1;} virtual unsigned int OptimalBlockSize() const {return 1;}
@ -559,7 +578,7 @@ protected:
//! . //! .
template <class T> template <class T>
class CRYPTOPP_NO_VTABLE SimpleKeyedTransformation : public T, public SimpleKeyingInterface class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyedTransformation : public T, public SimpleKeyingInterface
{ {
public: public:
void ThrowIfInvalidKeyLength(unsigned int length) void ThrowIfInvalidKeyLength(unsigned int length)
@ -579,6 +598,10 @@ class MessageAuthenticationCode : public HashTransformation, public SimpleKeying
typedef SimpleKeyedTransformation<BlockTransformation> BlockCipher; typedef SimpleKeyedTransformation<BlockTransformation> BlockCipher;
typedef SimpleKeyedTransformation<StreamTransformation> SymmetricCipher; typedef SimpleKeyedTransformation<StreamTransformation> SymmetricCipher;
typedef SimpleKeyedTransformation<HashTransformation> MessageAuthenticationCode; typedef SimpleKeyedTransformation<HashTransformation> MessageAuthenticationCode;
CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation<BlockTransformation>;
CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation<StreamTransformation>;
CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation<HashTransformation>;
#endif #endif
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
@ -588,7 +611,7 @@ typedef SymmetricCipher StreamCipher;
//! interface for random number generators //! interface for random number generators
/*! All return values are uniformly distributed over the range specified. /*! 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: public:
//! generate new random byte and return it //! 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 //! 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; class WaitObjectContainer;
@ -670,7 +693,7 @@ public:
\nosubgrouping \nosubgrouping
*/ */
class CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
{ {
public: public:
// placed up here for CW8 // placed up here for CW8
@ -929,11 +952,11 @@ BufferedTransformation & TheBitBucket();
//! interface for crypto material, such as public and private keys, and crypto parameters //! 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: public:
//! exception thrown when invalid crypto material is detected //! exception thrown when invalid crypto material is detected
class InvalidMaterial : public InvalidDataFormat class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
{ {
public: public:
explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {} 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 //! 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: public:
//! generate a random key or crypto parameters //! generate a random key or crypto parameters
@ -1005,25 +1028,25 @@ public:
//! interface for public keys //! 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 //! interface for private keys
class CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
{ {
}; };
//! interface for crypto prameters //! interface for crypto prameters
class CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
{ {
}; };
//! interface for asymmetric algorithms //! interface for asymmetric algorithms
class CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
{ {
public: public:
//! returns a reference to the crypto material used by this object //! returns a reference to the crypto material used by this object
@ -1041,7 +1064,7 @@ public:
//! interface for asymmetric algorithms using public keys //! interface for asymmetric algorithms using public keys
class CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
{ {
public: public:
// VC60 workaround: no co-variant return type // VC60 workaround: no co-variant return type
@ -1054,7 +1077,7 @@ public:
//! interface for asymmetric algorithms using private keys //! interface for asymmetric algorithms using private keys
class CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
{ {
public: public:
CryptoMaterial & AccessMaterial() {return AccessPrivateKey();} CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
@ -1066,7 +1089,7 @@ public:
//! interface for key agreement algorithms //! interface for key agreement algorithms
class CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
{ {
public: public:
CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();} CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
@ -1081,7 +1104,7 @@ public:
/*! This class provides an interface common to encryptors and decryptors /*! This class provides an interface common to encryptors and decryptors
for querying their plaintext and ciphertext lengths. for querying their plaintext and ciphertext lengths.
*/ */
class CRYPTOPP_NO_VTABLE PK_CryptoSystem class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
{ {
public: public:
virtual ~PK_CryptoSystem() {} virtual ~PK_CryptoSystem() {}
@ -1102,11 +1125,11 @@ public:
//! interface for public-key encryptors //! 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: public:
//! . //! .
class InvalidPlaintextLength : public Exception class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
{ {
public: public:
InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {} InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
@ -1126,7 +1149,7 @@ public:
//! interface for public-key decryptors //! 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: public:
//! decrypt a byte string, and return the length of plaintext //! decrypt a byte string, and return the length of plaintext
@ -1147,7 +1170,7 @@ public:
as RSA) whose ciphertext length and maximum plaintext length as RSA) whose ciphertext length and maximum plaintext length
depend only on the key. depend only on the key.
*/ */
class CRYPTOPP_NO_VTABLE PK_FixedLengthCryptoSystem class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_FixedLengthCryptoSystem
{ {
public: public:
//! //!
@ -1174,13 +1197,13 @@ class CRYPTOPP_NO_VTABLE PK_FixedLengthCryptoSystemImpl : public BASE, public PK
//! interface for encryptors with fixed length ciphertext //! interface for encryptors with fixed length ciphertext
class CRYPTOPP_NO_VTABLE PK_FixedLengthEncryptor : public PK_FixedLengthCryptoSystemImpl<PK_Encryptor> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_FixedLengthEncryptor : public PK_FixedLengthCryptoSystemImpl<PK_Encryptor>
{ {
}; };
//! interface for decryptors with fixed length ciphertext //! interface for decryptors with fixed length ciphertext
class CRYPTOPP_NO_VTABLE PK_FixedLengthDecryptor : public PK_FixedLengthCryptoSystemImpl<PK_Decryptor> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_FixedLengthDecryptor : public PK_FixedLengthCryptoSystemImpl<PK_Decryptor>
{ {
public: public:
//! decrypt a byte string, and return the length of plaintext //! 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 /*! This class provides an interface common to signers and verifiers
for querying scheme properties. for querying scheme properties.
*/ */
class CRYPTOPP_NO_VTABLE PK_SignatureScheme class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
{ {
public: 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 //! 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: public:
InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {} 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 //! 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: public:
KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {} KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
@ -1247,7 +1270,7 @@ public:
/*! Only Update() should be called /*! Only Update() should be called
on this class. No other functions inherited from HashTransformation 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: public:
//! should not be called on PK_MessageAccumulator //! should not be called on PK_MessageAccumulator
@ -1260,7 +1283,7 @@ public:
//! interface for public-key signers //! 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: public:
//! create a new HashTransformation to accumulate the message to be signed //! 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 and the signature contains a non-empty recoverable message part. The
Recovery* functions should be used in that case. 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: public:
//! create a new HashTransformation to accumulate the message to be verified //! 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 by two parties in a key agreement protocol, along with the algorithms
for generating key pairs and deriving agreed values. 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: public:
//! return length of agreed value produced //! return length of agreed value produced
@ -1382,7 +1405,7 @@ public:
key pairs. The long-lived key pair is called the static key pair, 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. 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: public:
//! return length of agreed value produced //! return length of agreed value produced
@ -1539,7 +1562,7 @@ public:
#endif #endif
//! BER Decode Exception Class, may be thrown during an ASN1 BER decode operation //! BER Decode Exception Class, may be thrown during an ASN1 BER decode operation
class BERDecodeErr : public InvalidArgument class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
{ {
public: public:
BERDecodeErr() : InvalidArgument("BER decode error") {} BERDecodeErr() : InvalidArgument("BER decode error") {}
@ -1547,7 +1570,7 @@ public:
}; };
//! interface for encoding and decoding ASN1 objects //! interface for encoding and decoding ASN1 objects
class CRYPTOPP_NO_VTABLE ASN1Object class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
{ {
public: public:
virtual ~ASN1Object() {} virtual ~ASN1Object() {}

109
cryptopp.rc Normal file
View File

@ -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

View File

@ -20,6 +20,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
#ifndef CRYPTOPP_IMPORTS
static inline bool CheckParity(byte b) static inline bool CheckParity(byte b)
{ {
unsigned int a = b ^ (b >> 4); 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); Block::Put(xorBlock, outBlock)(r)(l);
} }
#endif // #ifndef CRYPTOPP_IMPORTS
void DES_XEX3::Base::UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length) void DES_XEX3::Base::UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length)
{ {
AssertValidKeyLength(length); AssertValidKeyLength(length);

30
des.h
View File

@ -11,7 +11,7 @@ NAMESPACE_BEGIN(CryptoPP)
struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8> struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8>
{ {
static const char *StaticAlgorithmName() {return "DES";} CRYPTOPP_DLL static const char * StaticAlgorithmName() {return "DES";}
}; };
/// <a href="http://www.weidai.com/scan-mirror/cs.html#DES">DES</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#DES">DES</a>
@ -21,7 +21,7 @@ struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8>
check or correct the parity bits if you wish. */ check or correct the parity bits if you wish. */
class DES : public DES_Info, public BlockCipherDocumentation class DES : public DES_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<DES_Info> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length = 8); void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length = 8);
@ -42,19 +42,19 @@ public:
//! correct DES key parity bits //! correct DES key parity bits
static void CorrectKeyParityBits(byte *key); static void CorrectKeyParityBits(byte *key);
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
struct DES_EDE2_Info : public FixedBlockSize<8>, public FixedKeyLength<16> 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";}
}; };
/// <a href="http://www.weidai.com/scan-mirror/cs.html#DESede">DES-EDE2</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#DESede">DES-EDE2</a>
class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<DES_EDE2_Info> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE2_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length);
@ -65,19 +65,19 @@ class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
struct DES_EDE3_Info : public FixedBlockSize<8>, public FixedKeyLength<24> 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";}
}; };
/// <a href="http://www.weidai.com/scan-mirror/cs.html#DESede">DES-EDE3</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#DESede">DES-EDE3</a>
class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<DES_EDE3_Info> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE3_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length); void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length);
@ -88,8 +88,8 @@ class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24> struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24>
@ -100,7 +100,7 @@ struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24>
/// <a href="http://www.weidai.com/scan-mirror/cs.html#DESX">DES-XEX3</a>, AKA DESX /// <a href="http://www.weidai.com/scan-mirror/cs.html#DESX">DES-XEX3</a>, AKA DESX
class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<DES_XEX3_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_XEX3_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length); void UncheckedSetKey(CipherDir dir, const byte *key, unsigned int length);
@ -112,8 +112,8 @@ class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
typedef DES::Encryption DESEncryption; typedef DES::Encryption DESEncryption;

View File

@ -1,6 +1,9 @@
// This file is mostly generated by Phil Karn's gensp.c // This file is mostly generated by Phil Karn's gensp.c
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "des.h" #include "des.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -88,3 +91,5 @@ const word32 DES::Base::Spbox[8][64] = {
}; };
NAMESPACE_END NAMESPACE_END
#endif

5
dh.cpp
View File

@ -1,6 +1,9 @@
// dh.cpp - written and placed in the public domain by Wei Dai // dh.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "dh.h" #include "dh.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -12,3 +15,5 @@ void DH_TestInstantiations()
} }
NAMESPACE_END NAMESPACE_END
#endif

2
dh.h
View File

@ -85,6 +85,8 @@ private:
GroupParameters m_groupParameters; GroupParameters m_groupParameters;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime>;
//! <a href="http://www.weidai.com/scan-mirror/ka.html#DH">Diffie-Hellman</a> in GF(p) with key validation //! <a href="http://www.weidai.com/scan-mirror/ka.html#DH">Diffie-Hellman</a> in GF(p) with key validation
typedef DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime> DH; typedef DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime> DH;

View File

@ -17,7 +17,7 @@ struct Diamond2_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 1
/// <a href="http://www.weidai.com/scan-mirror/cs.html#Diamond2">Diamond2</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#Diamond2">Diamond2</a>
class Diamond2 : public Diamond2_Info, public BlockCipherDocumentation class Diamond2 : public Diamond2_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<Diamond2_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Diamond2_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length, unsigned int rounds); 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: public:
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
typedef Diamond2::Encryption Diamond2Encryption; typedef Diamond2::Encryption Diamond2Encryption;
@ -65,7 +65,7 @@ struct Diamond2Lite_Info : public FixedBlockSize<8>, public VariableKeyLength<16
/// <a href="http://www.weidai.com/scan-mirror/cs.html#Diamond2">Diamond2Lite</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#Diamond2">Diamond2Lite</a>
class Diamond2Lite : public Diamond2Lite_Info, public BlockCipherDocumentation class Diamond2Lite : public Diamond2Lite_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<Diamond2Lite_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Diamond2Lite_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length, unsigned int rounds); 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: public:
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
typedef Diamond2Lite::Encryption Diamond2LiteEncryption; typedef Diamond2Lite::Encryption Diamond2LiteEncryption;

100
dll.cpp Normal file
View File

@ -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 <windows.h>
#include <new.h>
#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<CryptoPP::SHA1>::DIGESTSIZE] = "reserved for mac";
static HMODULE s_hModule = NULL;
NAMESPACE_BEGIN(CryptoPP)
template<> const byte PKCS_DigestDecoration<SHA>::decoration[] = {0x30,0x21,0x30,0x09,0x06,0x05,0x2B,0x0E,0x03,0x02,0x1A,0x05,0x00,0x04,0x14};
template<> const unsigned int PKCS_DigestDecoration<SHA>::length = sizeof(PKCS_DigestDecoration<SHA>::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

64
dll.h Normal file
View File

@ -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 <new.h> // 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

178
dlltest.cpp Normal file
View File

@ -0,0 +1,178 @@
#include "dll.h"
#include <iostream>
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<DES>::Encryption encryption_DES_CBC;
encryption_DES_CBC.SetKeyWithIV(key, 8, iv);
encryption_DES_CBC.ProcessString(ciphertext, plaintext, 24);
CFB_Mode<DES>::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<DES_EDE3> 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

90
dlltest.dsp Normal file
View File

@ -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

2
dmac.h
View File

@ -35,7 +35,7 @@ private:
and Charles Rackoff. T should be BlockTransformation class. and Charles Rackoff. T should be BlockTransformation class.
*/ */
template <class T> template <class T>
class DMAC : public MessageAuthenticationCodeTemplate<DMAC_Base<T> > class DMAC : public MessageAuthenticationCodeFinal<DMAC_Base<T> >
{ {
public: public:
DMAC() {} DMAC() {}

View File

@ -1,6 +1,9 @@
// dsa.cpp - written and placed in the public domain by Wei Dai // dsa.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "dsa.h" #include "dsa.h"
#include "nbtheory.h" #include "nbtheory.h"
@ -112,3 +115,5 @@ bool DSA::GeneratePrimes(const byte *seedIn, unsigned int g, int &counter,
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -1,6 +1,9 @@
// ec2n.cpp - written and placed in the public domain by Wei Dai // ec2n.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "ec2n.h" #include "ec2n.h"
#include "asn.h" #include "asn.h"
@ -281,7 +284,6 @@ EC2N::Point EcPrecomputation<EC2N>::CascadeExponentiate(const Integer &exponent,
} }
*/ */
template class AbstractGroup<EC2N::Point>;
template class DL_FixedBasePrecomputationImpl<EC2N::Point>;
NAMESPACE_END NAMESPACE_END
#endif

12
ec2n.h
View File

@ -9,7 +9,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! Elliptic Curve Point //! Elliptic Curve Point
struct EC2NPoint struct CRYPTOPP_DLL EC2NPoint
{ {
EC2NPoint() : identity(true) {} EC2NPoint() : identity(true) {}
EC2NPoint(const PolynomialMod2 &x, const PolynomialMod2 &y) EC2NPoint(const PolynomialMod2 &x, const PolynomialMod2 &y)
@ -24,8 +24,10 @@ struct EC2NPoint
PolynomialMod2 x, y; PolynomialMod2 x, y;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<EC2NPoint>;
//! Elliptic Curve over GF(2^n) //! Elliptic Curve over GF(2^n)
class EC2N : public AbstractGroup<EC2NPoint> class CRYPTOPP_DLL EC2N : public AbstractGroup<EC2NPoint>
{ {
public: public:
typedef GF2NP Field; typedef GF2NP Field;
@ -73,12 +75,18 @@ public:
const FieldElement & GetA() const {return m_a;} const FieldElement & GetA() const {return m_a;}
const FieldElement & GetB() const {return m_b;} 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: private:
clonable_ptr<Field> m_field; clonable_ptr<Field> m_field;
FieldElement m_a, m_b; FieldElement m_a, m_b;
mutable Point m_R; mutable Point m_R;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl<EC2N::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation<EC2N::Point>;
template <class T> class EcPrecomputation; template <class T> class EcPrecomputation;
//! . //! .

View File

@ -1,14 +1,19 @@
// eccrypto.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "eccrypto.h" #include "eccrypto.h"
#include "ec2n.h"
#include "ecp.h"
#include "nbtheory.h" #include "nbtheory.h"
#include "oids.h" #include "oids.h"
#include "hex.h" #include "hex.h"
#include "argnames.h" #include "argnames.h"
#include "ec2n.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
#ifndef NDEBUG
static void ECDSA_TestInstantiations() static void ECDSA_TestInstantiations()
{ {
ECDSA<EC2N>::Signer t1; ECDSA<EC2N>::Signer t1;
@ -20,6 +25,7 @@ static void ECDSA_TestInstantiations()
ECDH<ECP>::Domain t7; ECDH<ECP>::Domain t7;
ECMQV<ECP>::Domain t8; ECMQV<ECP>::Domain t8;
} }
#endif
// VC60 workaround: complains when these functions are put into an anonymous namespace // VC60 workaround: complains when these functions are put into an anonymous namespace
static Integer ConvertToInteger(const PolynomialMod2 &x) static Integer ConvertToInteger(const PolynomialMod2 &x)
@ -627,13 +633,6 @@ void DL_PrivateKey_EC<EC>::DEREncodeKey(BufferedTransformation &bt) const
privateKey.MessageEnd(); privateKey.MessageEnd();
} }
// ******************************************************************
template class DL_GroupParameters_EC<EC2N>;
template class DL_GroupParameters_EC<ECP>;
template class DL_PublicKey_EC<EC2N>;
template class DL_PublicKey_EC<ECP>;
template class DL_PrivateKey_EC<EC2N>;
template class DL_PrivateKey_EC<ECP>;
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -1,5 +1,5 @@
#ifndef CRYPTOPP_ECCRYPTO_H #ifndef CRYPTOPP_ECCRYPTO_H
#define CRYPTOPP_ECCRTPTO_H #define CRYPTOPP_ECCRYPTO_H
/*! \file /*! \file
*/ */
@ -12,11 +12,11 @@
#include "gfpcrypt.h" #include "gfpcrypt.h"
#include "dh.h" #include "dh.h"
#include "mqv.h" #include "mqv.h"
#include "ecp.h"
#include "ec2n.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
template <class T> class EcPrecomputation;
//! Elliptic Curve Parameters //! Elliptic Curve Parameters
/*! This class corresponds to the ASN.1 sequence of the same name /*! This class corresponds to the ASN.1 sequence of the same name
in ANSI X9.62 (also SEC 1). in ANSI X9.62 (also SEC 1).
@ -117,6 +117,9 @@ public:
const EllipticCurve& GetCurve() const {return m_groupPrecomputation.GetCurve();} const EllipticCurve& GetCurve() const {return m_groupPrecomputation.GetCurve();}
bool operator==(const ThisClass &rhs) const
{return DL_GroupParametersImpl<EcPrecomputation<EC> >::operator==(rhs);}
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
const Point& GetBasePoint() const {return GetSubgroupGenerator();} const Point& GetBasePoint() const {return GetSubgroupGenerator();}
const Integer& GetBasePointOrder() const {return GetSubgroupOrder();} const Integer& GetBasePointOrder() const {return GetSubgroupOrder();}
@ -133,6 +136,11 @@ protected:
mutable Integer m_k; // cofactor mutable Integer m_k; // cofactor
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<ECP> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKeyImpl<DL_GroupParameters_EC<EC2N> >;
//! . //! .
template <class EC> template <class EC>
class DL_PublicKey_EC : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> > class DL_PublicKey_EC : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
@ -150,6 +158,11 @@ public:
void DEREncodeKey(BufferedTransformation &bt) const; void DEREncodeKey(BufferedTransformation &bt) const;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_EC<EC2N>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<ECP> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKeyImpl<DL_GroupParameters_EC<EC2N> >;
//! . //! .
template <class EC> template <class EC>
class DL_PrivateKey_EC : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> > class DL_PrivateKey_EC : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
@ -171,6 +184,9 @@ public:
void DEREncodeKey(BufferedTransformation &bt) const; void DEREncodeKey(BufferedTransformation &bt) const;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<ECP>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_EC<EC2N>;
//! Elliptic Curve Diffie-Hellman, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#ECDH">ECDH</a> //! Elliptic Curve Diffie-Hellman, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#ECDH">ECDH</a>
template <class EC, class COFACTOR_OPTION = CPP_TYPENAME DL_GroupParameters_EC<EC>::DefaultCofactorOption> template <class EC, class COFACTOR_OPTION = CPP_TYPENAME DL_GroupParameters_EC<EC>::DefaultCofactorOption>
struct ECDH struct ECDH
@ -196,6 +212,9 @@ struct DL_Keys_EC
template <class EC, class H = SHA> template <class EC, class H = SHA>
struct ECDSA; struct ECDSA;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<ECP>, ECDSA<ECP> >;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC2N>, ECDSA<EC2N> >;
//! . //! .
template <class EC> template <class EC>
struct DL_Keys_ECDSA struct DL_Keys_ECDSA
@ -204,6 +223,9 @@ struct DL_Keys_ECDSA
typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC> > PrivateKey; typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC> > PrivateKey;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<ECP::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<EC2N::Point>;
//! . //! .
template <class EC> template <class EC>
class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point> class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point>

17
ecp.cpp
View File

@ -1,12 +1,14 @@
// ecp.cpp - written and placed in the public domain by Wei Dai // ecp.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "ecp.h" #include "ecp.h"
#include "asn.h" #include "asn.h"
#include "nbtheory.h" #include "nbtheory.h"
#include "algebra.cpp" #include "algebra.cpp"
#include "eprecomp.cpp"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -463,15 +465,6 @@ ECP::Point ECP::CascadeScalarMultiply(const Point &P, const Integer &k1, const P
return AbstractGroup<Point>::CascadeScalarMultiply(P, k1, Q, k2); return AbstractGroup<Point>::CascadeScalarMultiply(P, k1, Q, k2);
} }
// ********************************************************
void EcPrecomputation<ECP>::SetCurve(const ECP &ec)
{
m_ec.reset(new ECP(ec, true));
m_ecOriginal = ec;
}
template class AbstractGroup<ECP::Point>;
template class DL_FixedBasePrecomputationImpl<ECP::Point>;
NAMESPACE_END NAMESPACE_END
#endif

18
ecp.h
View File

@ -9,7 +9,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! Elliptical Curve Point //! Elliptical Curve Point
struct ECPPoint struct CRYPTOPP_DLL ECPPoint
{ {
ECPPoint() : identity(true) {} ECPPoint() : identity(true) {}
ECPPoint(const Integer &x, const Integer &y) ECPPoint(const Integer &x, const Integer &y)
@ -24,8 +24,10 @@ struct ECPPoint
Integer x, y; Integer x, y;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<ECPPoint>;
//! Elliptic Curve over GF(p), where p is prime //! Elliptic Curve over GF(p), where p is prime
class ECP : public AbstractGroup<ECPPoint> class CRYPTOPP_DLL ECP : public AbstractGroup<ECPPoint>
{ {
public: public:
typedef ModularArithmetic Field; typedef ModularArithmetic Field;
@ -77,12 +79,18 @@ public:
const FieldElement & GetA() const {return m_a;} const FieldElement & GetA() const {return m_a;}
const FieldElement & GetB() const {return m_b;} 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: private:
clonable_ptr<Field> m_fieldPtr; clonable_ptr<Field> m_fieldPtr;
FieldElement m_a, m_b; FieldElement m_a, m_b;
mutable Point m_R; mutable Point m_R;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl<ECP::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation<ECP::Point>;
template <class T> class EcPrecomputation; template <class T> class EcPrecomputation;
//! . //! .
@ -102,7 +110,11 @@ public:
void DEREncodeElement(BufferedTransformation &bt, const Element &v) const {m_ec->DEREncodePoint(bt, v, false);} void DEREncodeElement(BufferedTransformation &bt, const Element &v) const {m_ec->DEREncodePoint(bt, v, false);}
// non-inherited // 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;} const ECP & GetCurve() const {return *m_ecOriginal;}
private: private:

View File

@ -1,6 +1,9 @@
// eprecomp.cpp - written and placed in the public domain by Wei Dai // eprecomp.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "eprecomp.h" #include "eprecomp.h"
#include "asn.h" #include "asn.h"
@ -105,3 +108,5 @@ template <class T> T
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -1,6 +1,9 @@
// files.cpp - written and placed in the public domain by Wei Dai // files.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "files.h" #include "files.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -16,16 +19,15 @@ void Files_TestInstantiations()
void FileStore::StoreInitialize(const NameValuePairs &parameters) void FileStore::StoreInitialize(const NameValuePairs &parameters)
{ {
m_file.close(); m_file.reset(new std::ifstream);
m_file.clear();
const char *fileName; const char *fileName;
if (parameters.GetValue(Name::InputFileName(), fileName)) if (parameters.GetValue(Name::InputFileName(), fileName))
{ {
ios::openmode binary = parameters.GetValueWithDefault(Name::InputBinaryMode(), true) ? ios::binary : ios::openmode(0); ios::openmode binary = parameters.GetValueWithDefault(Name::InputBinaryMode(), true) ? ios::binary : ios::openmode(0);
m_file.open(fileName, ios::in | binary); m_file->open(fileName, ios::in | binary);
if (!m_file) if (!*m_file)
throw OpenErr(fileName); throw OpenErr(fileName);
m_stream = &m_file; m_stream = m_file.get();
} }
else else
{ {
@ -148,14 +150,15 @@ unsigned long FileStore::Skip(unsigned long skipMax)
void FileSink::IsolatedInitialize(const NameValuePairs &parameters) void FileSink::IsolatedInitialize(const NameValuePairs &parameters)
{ {
m_file.reset(new std::ofstream);
const char *fileName; const char *fileName;
if (parameters.GetValue(Name::OutputFileName(), fileName)) if (parameters.GetValue(Name::OutputFileName(), fileName))
{ {
ios::openmode binary = parameters.GetValueWithDefault(Name::OutputBinaryMode(), true) ? ios::binary : ios::openmode(0); ios::openmode binary = parameters.GetValueWithDefault(Name::OutputBinaryMode(), true) ? ios::binary : ios::openmode(0);
m_file.open(fileName, ios::out | ios::trunc | binary); m_file->open(fileName, ios::out | ios::trunc | binary);
if (!m_file) if (!*m_file)
throw OpenErr(fileName); throw OpenErr(fileName);
m_stream = &m_file; m_stream = m_file.get();
} }
else else
{ {
@ -193,3 +196,5 @@ unsigned int FileSink::Put2(const byte *inString, unsigned int length, int messa
} }
NAMESPACE_END NAMESPACE_END
#endif

10
files.h
View File

@ -11,7 +11,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! . //! .
class FileStore : public Store, private FilterPutSpaceHelper class CRYPTOPP_DLL FileStore : public Store, private FilterPutSpaceHelper, public NotCopyable
{ {
public: public:
class Err : public Exception class Err : public Exception
@ -38,7 +38,7 @@ public:
private: private:
void StoreInitialize(const NameValuePairs &parameters); void StoreInitialize(const NameValuePairs &parameters);
std::ifstream m_file; member_ptr<std::ifstream> m_file;
std::istream *m_stream; std::istream *m_stream;
byte *m_space; byte *m_space;
unsigned int m_len; unsigned int m_len;
@ -46,7 +46,7 @@ private:
}; };
//! . //! .
class FileSource : public SourceTemplate<FileStore> class CRYPTOPP_DLL FileSource : public SourceTemplate<FileStore>
{ {
public: public:
typedef FileStore::Err Err; typedef FileStore::Err Err;
@ -64,7 +64,7 @@ public:
}; };
//! . //! .
class FileSink : public Sink class CRYPTOPP_DLL FileSink : public Sink, public NotCopyable
{ {
public: public:
class Err : public Exception class Err : public Exception
@ -88,7 +88,7 @@ public:
bool IsolatedFlush(bool hardFlush, bool blocking); bool IsolatedFlush(bool hardFlush, bool blocking);
private: private:
std::ofstream m_file; member_ptr<std::ofstream> m_file;
std::ostream *m_stream; std::ostream *m_stream;
}; };

View File

@ -1,6 +1,9 @@
// filters.cpp - written and placed in the public domain by Wei Dai // filters.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "filters.h" #include "filters.h"
#include "mqueue.h" #include "mqueue.h"
#include "fltrimpl.h" #include "fltrimpl.h"
@ -931,3 +934,5 @@ unsigned int NullStore::TransferTo2(BufferedTransformation &target, unsigned lon
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -11,7 +11,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
/// provides an implementation of BufferedTransformation's attachment interface /// 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: public:
Filter(BufferedTransformation *attachment); Filter(BufferedTransformation *attachment);
@ -52,7 +52,7 @@ protected:
int m_continueAt; 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 // 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) 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 //! measure how many byte and messages pass through, also serves as valve
class MeterFilter : public Bufferless<Filter> class CRYPTOPP_DLL MeterFilter : public Bufferless<Filter>
{ {
public: public:
MeterFilter(BufferedTransformation *attachment=NULL, bool transparent=true) MeterFilter(BufferedTransformation *attachment=NULL, bool transparent=true)
@ -111,14 +111,14 @@ private:
}; };
//! . //! .
class TransparentFilter : public MeterFilter class CRYPTOPP_DLL TransparentFilter : public MeterFilter
{ {
public: public:
TransparentFilter(BufferedTransformation *attachment=NULL) : MeterFilter(attachment, true) {} TransparentFilter(BufferedTransformation *attachment=NULL) : MeterFilter(attachment, true) {}
}; };
//! . //! .
class OpaqueFilter : public MeterFilter class CRYPTOPP_DLL OpaqueFilter : public MeterFilter
{ {
public: public:
OpaqueFilter(BufferedTransformation *attachment=NULL) : MeterFilter(attachment, false) {} OpaqueFilter(BufferedTransformation *attachment=NULL) : MeterFilter(attachment, false) {}
@ -129,7 +129,7 @@ public:
First and last blocks are optional, and middle blocks may First and last blocks are optional, and middle blocks may
be a stream instead (i.e. blockSize == 1). be a stream instead (i.e. blockSize == 1).
*/ */
class FilterWithBufferedInput : public Filter class CRYPTOPP_DLL FilterWithBufferedInput : public Filter
{ {
public: public:
FilterWithBufferedInput(BufferedTransformation *attachment); FilterWithBufferedInput(BufferedTransformation *attachment);
@ -212,7 +212,7 @@ private:
}; };
//! . //! .
class FilterWithInputQueue : public Filter class CRYPTOPP_DLL FilterWithInputQueue : public Filter
{ {
public: public:
FilterWithInputQueue(BufferedTransformation *attachment) : Filter(attachment) {} FilterWithInputQueue(BufferedTransformation *attachment) : Filter(attachment) {}
@ -238,7 +238,7 @@ protected:
}; };
//! Filter Wrapper for StreamTransformation //! Filter Wrapper for StreamTransformation
class StreamTransformationFilter : public FilterWithBufferedInput, private FilterPutSpaceHelper class CRYPTOPP_DLL StreamTransformationFilter : public FilterWithBufferedInput, private FilterPutSpaceHelper
{ {
public: public:
enum BlockPaddingScheme {NO_PADDING, ZEROS_PADDING, PKCS_PADDING, ONE_AND_ZEROS_PADDING, DEFAULT_PADDING}; enum BlockPaddingScheme {NO_PADDING, ZEROS_PADDING, PKCS_PADDING, ONE_AND_ZEROS_PADDING, DEFAULT_PADDING};
@ -265,7 +265,7 @@ typedef StreamTransformationFilter StreamCipherFilter;
#endif #endif
//! Filter Wrapper for HashTransformation //! Filter Wrapper for HashTransformation
class HashFilter : public Bufferless<Filter>, private FilterPutSpaceHelper class CRYPTOPP_DLL HashFilter : public Bufferless<Filter>, private FilterPutSpaceHelper
{ {
public: public:
HashFilter(HashTransformation &hm, BufferedTransformation *attachment = NULL, bool putMessage=false) HashFilter(HashTransformation &hm, BufferedTransformation *attachment = NULL, bool putMessage=false)
@ -283,7 +283,7 @@ private:
}; };
//! Filter Wrapper for HashTransformation //! Filter Wrapper for HashTransformation
class HashVerificationFilter : public FilterWithBufferedInput class CRYPTOPP_DLL HashVerificationFilter : public FilterWithBufferedInput
{ {
public: public:
class HashVerificationFailed : public Exception class HashVerificationFailed : public Exception
@ -317,7 +317,7 @@ private:
typedef HashVerificationFilter HashVerifier; // for backwards compatibility typedef HashVerificationFilter HashVerifier; // for backwards compatibility
//! Filter Wrapper for PK_Signer //! Filter Wrapper for PK_Signer
class SignerFilter : public Unflushable<Filter> class CRYPTOPP_DLL SignerFilter : public Unflushable<Filter>
{ {
public: public:
SignerFilter(RandomNumberGenerator &rng, const PK_Signer &signer, BufferedTransformation *attachment = NULL, bool putMessage=false) SignerFilter(RandomNumberGenerator &rng, const PK_Signer &signer, BufferedTransformation *attachment = NULL, bool putMessage=false)
@ -335,7 +335,7 @@ private:
}; };
//! Filter Wrapper for PK_Verifier //! Filter Wrapper for PK_Verifier
class SignatureVerificationFilter : public FilterWithBufferedInput class CRYPTOPP_DLL SignatureVerificationFilter : public FilterWithBufferedInput
{ {
public: public:
class SignatureVerificationFailed : public Exception class SignatureVerificationFailed : public Exception
@ -367,7 +367,7 @@ private:
typedef SignatureVerificationFilter VerifierFilter; // for backwards compatibility typedef SignatureVerificationFilter VerifierFilter; // for backwards compatibility
//! Redirect input to another BufferedTransformation without owning it //! Redirect input to another BufferedTransformation without owning it
class Redirector : public CustomSignalPropagation<Sink> class CRYPTOPP_DLL Redirector : public CustomSignalPropagation<Sink>
{ {
public: public:
enum Behavior enum Behavior
@ -429,7 +429,7 @@ private:
}; };
// Used By ProxyFilter // Used By ProxyFilter
class OutputProxy : public CustomSignalPropagation<Sink> class CRYPTOPP_DLL OutputProxy : public CustomSignalPropagation<Sink>
{ {
public: public:
OutputProxy(BufferedTransformation &owner, bool passSignal) : m_owner(owner), m_passSignal(passSignal) {} 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. //! 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: public:
ProxyFilter(BufferedTransformation *filter, unsigned int firstSize, unsigned int lastSize, BufferedTransformation *attachment); 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 //! 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: public:
SimpleProxyFilter(BufferedTransformation *filter, BufferedTransformation *attachment) SimpleProxyFilter(BufferedTransformation *filter, BufferedTransformation *attachment)
@ -495,7 +495,7 @@ public:
//! proxy for the filter created by PK_Encryptor::CreateEncryptionFilter //! proxy for the filter created by PK_Encryptor::CreateEncryptionFilter
/*! This class is here just to provide symmetry with VerifierFilter. */ /*! This class is here just to provide symmetry with VerifierFilter. */
class PK_EncryptorFilter : public SimpleProxyFilter class CRYPTOPP_DLL PK_EncryptorFilter : public SimpleProxyFilter
{ {
public: public:
PK_EncryptorFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment = NULL) 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 //! proxy for the filter created by PK_Decryptor::CreateDecryptionFilter
/*! This class is here just to provide symmetry with SignerFilter. */ /*! This class is here just to provide symmetry with SignerFilter. */
class PK_DecryptorFilter : public SimpleProxyFilter class CRYPTOPP_DLL PK_DecryptorFilter : public SimpleProxyFilter
{ {
public: public:
PK_DecryptorFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment = NULL) PK_DecryptorFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment = NULL)
@ -542,10 +542,11 @@ private:
}; };
//! Append input to an std::string //! Append input to an std::string
CRYPTOPP_DLL_TEMPLATE_CLASS StringSinkTemplate<std::string>;
typedef StringSinkTemplate<std::string> StringSink; typedef StringSinkTemplate<std::string> StringSink;
//! Copy input to a memory buffer //! Copy input to a memory buffer
class ArraySink : public Bufferless<Sink> class CRYPTOPP_DLL ArraySink : public Bufferless<Sink>
{ {
public: public:
ArraySink(const NameValuePairs &parameters = g_nullNameValuePairs) {IsolatedInitialize(parameters);} ArraySink(const NameValuePairs &parameters = g_nullNameValuePairs) {IsolatedInitialize(parameters);}
@ -565,7 +566,7 @@ protected:
}; };
//! Xor input to a memory buffer //! Xor input to a memory buffer
class ArrayXorSink : public ArraySink class CRYPTOPP_DLL ArrayXorSink : public ArraySink
{ {
public: public:
ArrayXorSink(byte *buf, unsigned int size) ArrayXorSink(byte *buf, unsigned int size)
@ -586,18 +587,18 @@ public:
template <class T> StringStore(const T &string) template <class T> StringStore(const T &string)
{StoreInitialize(MakeParameters("InputBuffer", ConstByteArrayParameter(string)));} {StoreInitialize(MakeParameters("InputBuffer", ConstByteArrayParameter(string)));}
unsigned int TransferTo2(BufferedTransformation &target, unsigned long &transferBytes, const std::string &channel=NULL_CHANNEL, bool blocking=true); CRYPTOPP_DLL 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 CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end=ULONG_MAX, const std::string &channel=NULL_CHANNEL, bool blocking=true) const;
private: private:
void StoreInitialize(const NameValuePairs &parameters); CRYPTOPP_DLL void StoreInitialize(const NameValuePairs &parameters);
const byte *m_store; const byte *m_store;
unsigned int m_length, m_count; unsigned int m_length, m_count;
}; };
//! . //! .
class RandomNumberStore : public Store class CRYPTOPP_DLL RandomNumberStore : public Store
{ {
public: public:
RandomNumberStore(RandomNumberGenerator &rng, unsigned long length) RandomNumberStore(RandomNumberGenerator &rng, unsigned long length)
@ -621,7 +622,7 @@ private:
}; };
//! . //! .
class NullStore : public Store class CRYPTOPP_DLL NullStore : public Store
{ {
public: public:
NullStore(unsigned long size = ULONG_MAX) : m_size(size) {} NullStore(unsigned long size = ULONG_MAX) : m_size(size) {}
@ -635,7 +636,7 @@ private:
}; };
//! A Filter that pumps data into its attachment as input //! A Filter that pumps data into its attachment as input
class CRYPTOPP_NO_VTABLE Source : public InputRejecting<Filter> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Source : public InputRejecting<Filter>
{ {
public: public:
Source(BufferedTransformation *attachment) Source(BufferedTransformation *attachment)
@ -690,7 +691,7 @@ protected:
}; };
//! . //! .
class StringSource : public SourceTemplate<StringStore> class CRYPTOPP_DLL StringSource : public SourceTemplate<StringStore>
{ {
public: public:
StringSource(BufferedTransformation *attachment = NULL) StringSource(BufferedTransformation *attachment = NULL)
@ -699,17 +700,12 @@ public:
: SourceTemplate<StringStore>(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string)));} : SourceTemplate<StringStore>(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string)));}
StringSource(const byte *string, unsigned int length, bool pumpAll, BufferedTransformation *attachment = NULL) StringSource(const byte *string, unsigned int length, bool pumpAll, BufferedTransformation *attachment = NULL)
: SourceTemplate<StringStore>(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string, length)));} : SourceTemplate<StringStore>(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string, length)));}
#ifdef __MWERKS__ // CW60 workaround
StringSource(const std::string &string, bool pumpAll, BufferedTransformation *attachment = NULL) StringSource(const std::string &string, bool pumpAll, BufferedTransformation *attachment = NULL)
#else
template <class T> StringSource(const T &string, bool pumpAll, BufferedTransformation *attachment = NULL)
#endif
: SourceTemplate<StringStore>(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string)));} : SourceTemplate<StringStore>(attachment) {SourceInitialize(pumpAll, MakeParameters("InputBuffer", ConstByteArrayParameter(string)));}
}; };
//! . //! .
class RandomNumberSource : public SourceTemplate<RandomNumberStore> class CRYPTOPP_DLL RandomNumberSource : public SourceTemplate<RandomNumberStore>
{ {
public: public:
RandomNumberSource(RandomNumberGenerator &rng, unsigned int length, bool pumpAll, BufferedTransformation *attachment = NULL) RandomNumberSource(RandomNumberGenerator &rng, unsigned int length, bool pumpAll, BufferedTransformation *attachment = NULL)

View File

@ -1,6 +1,9 @@
// fips140.cpp - written and placed in the public domain by Wei Dai // fips140.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "fips140.h" #include "fips140.h"
#include "trdlocal.h" // needs to be included last for cygwin #include "trdlocal.h" // needs to be included last for cygwin
@ -32,7 +35,7 @@ void SimulatePowerUpSelfTestFailure()
g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_FAILED; g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_FAILED;
} }
PowerUpSelfTestStatus GetPowerUpSelfTestStatus() PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus()
{ {
return g_powerUpSelfTestStatus; return g_powerUpSelfTestStatus;
} }
@ -77,3 +80,5 @@ void SignaturePairwiseConsistencyTest_FIPS_140_Only(const PK_Signer &signer, con
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -10,26 +10,36 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! exception thrown when a crypto algorithm is used after a self test fails //! exception thrown when a crypto algorithm is used after a self test fails
class SelfTestFailure : public Exception class CRYPTOPP_DLL SelfTestFailure : public Exception
{ {
public: public:
explicit SelfTestFailure(const std::string &s) : Exception(OTHER_ERROR, s) {} explicit SelfTestFailure(const std::string &s) : Exception(OTHER_ERROR, s) {}
}; };
//! returns whether FIPS 140-2 compliance features were enabled at compile time //! 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 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}; 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 //! 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 //! 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 //! 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 // this is used by Algorithm constructor to allow Algorithm objects to be constructed for the self test
bool PowerUpSelfTestInProgressOnThisThread(); bool PowerUpSelfTestInProgressOnThisThread();

View File

@ -1,27 +1,24 @@
// fipstest.cpp - written and placed in the public domain by Wei Dai // fipstest.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#include "fips140.h"
#include "sha.h" #ifndef CRYPTOPP_IMPORTS
#include "files.h"
#include "hex.h" #include "dll.h"
#include "rsa.h" #include <windows.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
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
extern PowerUpSelfTestStatus g_powerUpSelfTestStatus; 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) void KnownAnswerTest(RandomNumberGenerator &rng, const char *output)
{ {
@ -105,22 +102,22 @@ void SymmetricEncryptionKnownAnswerTest(
void KnownAnswerTest(HashTransformation &hash, const char *message, const char *digest) void KnownAnswerTest(HashTransformation &hash, const char *message, const char *digest)
{ {
EqualityComparisonFilter comparison; EqualityComparisonFilter comparison;
StringSource(message, true, new HashFilter(hash, new ChannelSwitch(comparison, "0")));
StringSource(digest, true, new HexDecoder(new ChannelSwitch(comparison, "1"))); StringSource(digest, true, new HexDecoder(new ChannelSwitch(comparison, "1")));
StringSource(message, true, new HashFilter(hash, new ChannelSwitch(comparison, "0")));
comparison.ChannelMessageSeriesEnd("0"); comparison.ChannelMessageSeriesEnd("0");
comparison.ChannelMessageSeriesEnd("1"); comparison.ChannelMessageSeriesEnd("1");
} }
template <class HASH> template <class HASH>
void SecureHashKnownAnswerTest(const char *message, const char *digest) void SecureHashKnownAnswerTest(const char *message, const char *digest, HASH *dummy = NULL)
{ {
HASH hash; HASH hash;
KnownAnswerTest(hash, message, digest); KnownAnswerTest(hash, message, digest);
} }
template <class MAC> template <class MAC>
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; std::string decodedKey;
StringSource(key, true, new HexDecoder(new StringSink(decodedKey))); StringSource(key, true, new HexDecoder(new StringSink(decodedKey)));
@ -219,19 +216,26 @@ void SignaturePairwiseConsistencyTest(const char *key, SCHEME *dummy = NULL)
SignaturePairwiseConsistencyTest(signer, verifier); SignaturePairwiseConsistencyTest(signer, verifier);
} }
void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha1Digest) MessageAuthenticationCode * NewIntegrityCheckingMAC()
{ {
g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_NOT_DONE; byte key[] = {0x47, 0x1E, 0x33, 0x96, 0x65, 0xB1, 0x6A, 0xED, 0x0B, 0xF8, 0x6B, 0xFD, 0x01, 0x65, 0x05, 0xCC};
SetPowerUpSelfTestInProgressOnThisThread(true); return new HMAC<SHA1>(key, sizeof(key));
}
try bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation)
{ {
if (FIPS_140_2_ComplianceEnabled() || moduleFilename != NULL) std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC());
{ unsigned int macSize = mac->DigestSize();
// integrity test
SHA1 sha; SecByteBlock tempMac;
HashVerifier verifier(sha); SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac;
verifier.Put(expectedModuleSha1Digest, sha.DigestSize()); 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); FileStore file(moduleFilename);
#ifdef CRYPTOPP_WIN32_AVAILABLE #ifdef CRYPTOPP_WIN32_AVAILABLE
@ -245,13 +249,13 @@ void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha
while (nSections--) while (nSections--)
{ {
DWORD sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize);
switch (phs->Characteristics) switch (phs->Characteristics)
{ {
default: default:
break; break;
case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ:
case IMAGE_SCN_CNT_INITIALIZED_DATA | 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; const byte *memStart = (const byte *)h + phs->VirtualAddress;
DWORD fileStart = phs->PointerToRawData; DWORD fileStart = phs->PointerToRawData;
if (phs->VirtualAddress == phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress) if (phs->VirtualAddress == phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT].VirtualAddress)
@ -263,6 +267,14 @@ void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha
sectionSize -= iatSize; sectionSize -= iatSize;
} }
file.TransferTo(verifier, fileStart - currentFilePos); 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); verifier.Put(memStart, sectionSize);
::VirtualUnlock((LPVOID)memStart, sectionSize); // release the memory from working set ::VirtualUnlock((LPVOID)memStart, sectionSize); // release the memory from working set
file.Skip(sectionSize); file.Skip(sectionSize);
@ -276,25 +288,43 @@ void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha
#ifdef CRYPTOPP_WIN32_AVAILABLE #ifdef CRYPTOPP_WIN32_AVAILABLE
// if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory),
// hash from disk instead // hash from disk instead
if (!verifier.GetLastResult()) if (memcmp(expectedModuleMac, actualMac, macSize) != 0)
{ {
OutputDebugString("In memory EDC test failed. This may be caused by debug breakpoints or DLL relocation.\n"); OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n");
verifier.Put(expectedModuleSha1Digest, sha.DigestSize()); file.Initialize(MakeParameters("InputFileName", moduleFilename));
file.Initialize(MakeParameters(Name::InputFileName(), moduleFilename)); verifier.Detach(new ArraySink(actualMac, actualMac.size()));
if (macFileLocation)
{
file.TransferTo(verifier, macFileLocation);
file.Skip(macSize);
}
file.TransferAllTo(verifier); file.TransferAllTo(verifier);
} }
#endif #endif
if (!verifier.GetLastResult()) if (memcmp(expectedModuleMac, actualMac, macSize) == 0)
{ return true;
#ifdef CRYPTOPP_WIN32_AVAILABLE #ifdef CRYPTOPP_WIN32_AVAILABLE
std::string actualDigest; std::string hexMac;
FileSource(moduleFilename, true, new HashFilter(sha, new HexEncoder(new StringSink(actualDigest)))); HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size());
OutputDebugString(("Crypto++ EDC test failed. Actual digest is: " + actualDigest + "\n").c_str()); OutputDebugString((moduleFilename + (" integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str());
#endif #endif
return false;
}
void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleMac)
{
g_powerUpSelfTestStatus = POWER_UP_SELF_TEST_NOT_DONE;
SetPowerUpSelfTestInProgressOnThisThread(true);
try
{
if (FIPS_140_2_ComplianceEnabled() || moduleFilename != NULL)
{
if (!IntegrityCheckModule(moduleFilename, expectedModuleMac, &g_actualMac, &g_macFileLocation))
throw 0; // throw here so we break in the debugger, this will be caught right away throw 0; // throw here so we break in the debugger, this will be caught right away
} }
}
// algorithm tests // algorithm tests
@ -359,11 +389,38 @@ void DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleSha
"abc", "abc",
"A9993E364706816ABA3E25717850C26C9CD0D89D"); "A9993E364706816ABA3E25717850C26C9CD0D89D");
SecureHashKnownAnswerTest<SHA256>(
"abc",
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
SecureHashKnownAnswerTest<SHA384>(
"abc",
"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7");
SecureHashKnownAnswerTest<SHA512>(
"abc",
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
MAC_KnownAnswerTest<HMAC<SHA> >( MAC_KnownAnswerTest<HMAC<SHA> >(
"303132333435363738393a3b3c3d3e3f40414243", "303132333435363738393a3b3c3d3e3f40414243",
"Sample #2", "Sample #2",
"0922d3405faa3d194f82a45830737d5cc6c75d24"); "0922d3405faa3d194f82a45830737d5cc6c75d24");
MAC_KnownAnswerTest<HMAC<SHA256> >(
"303132333435363738393a3b3c3d3e3f40414243",
"abc",
"D28363F335B2DAE468793A38680DEA9F7FB8BE1DCEDA197CDB3B1CB59A9F6422");
MAC_KnownAnswerTest<HMAC<SHA384> >(
"303132333435363738393a3b3c3d3e3f40414243",
"abc",
"E7740C592F1414C969190EFACF51FC8BE1CB52F5DC5E686200D2CA1773D151DB19C59112371CE374165A6BF72AEF69D0");
MAC_KnownAnswerTest<HMAC<SHA512> >(
"303132333435363738393a3b3c3d3e3f40414243",
"abc",
"BF07864E733B995862F3C2D432C7FF2F5EB073FFFC4F880CD94D5D21086476B7428F27BE694A9D9CB3BB500FE1255852BAFCBAF4042390B3706CDF02421B51AC");
SignatureKnownAnswerTest<RSASS<PKCS1v15, SHA> >( SignatureKnownAnswerTest<RSASS<PKCS1v15, SHA> >(
"30820150020100300d06092a864886f70d01010105000482013a3082013602010002400a66791dc6988168de7ab77419bb7fb0" "30820150020100300d06092a864886f70d01010105000482013a3082013602010002400a66791dc6988168de7ab77419bb7fb0"
"c001c62710270075142942e19a8d8c51d053b3e3782a1de5dc5af4ebe99468170114a1dfe67cdc9a9af55d655620bbab0203010001" "c001c62710270075142942e19a8d8c51d053b3e3782a1de5dc5af4ebe99468170114a1dfe67cdc9a9af55d655620bbab0203010001"
@ -398,3 +455,5 @@ done:
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -1,17 +1,18 @@
// gf2n.cpp - written and placed in the public domain by Wei Dai // gf2n.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "gf2n.h" #include "gf2n.h"
#include "algebra.h" #include "algebra.h"
#include "words.h" #include "words.h"
#include "rng.h" #include "randpool.h"
#include "asn.h" #include "asn.h"
#include "oids.h" #include "oids.h"
#include <iostream> #include <iostream>
#include "algebra.cpp"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
PolynomialMod2::PolynomialMod2() PolynomialMod2::PolynomialMod2()
@ -551,10 +552,10 @@ GF2NP::Element GF2NP::SolveQuadraticEquation(const Element &a) const
if (m%2 == 0) if (m%2 == 0)
{ {
Element z, w; Element z, w;
RandomPool rng;
do do
{ {
LC_RNG rng(11111); Element p((RandomNumberGenerator &)rng, m);
Element p(rng, m);
z = PolynomialMod2::Zero(); z = PolynomialMod2::Zero();
w = p; w = p;
for (unsigned int i=1; i<=m-1; i++) for (unsigned int i=1; i<=m-1; i++)
@ -868,3 +869,5 @@ GF2NP * BERDecodeGF2NP(BufferedTransformation &bt)
} }
NAMESPACE_END NAMESPACE_END
#endif

15
gf2n.h
View File

@ -14,7 +14,7 @@ NAMESPACE_BEGIN(CryptoPP)
//! Polynomial with Coefficients in GF(2) //! Polynomial with Coefficients in GF(2)
/*! \nosubgrouping */ /*! \nosubgrouping */
class PolynomialMod2 class CRYPTOPP_DLL PolynomialMod2
{ {
public: public:
//! \name ENUMS, EXCEPTIONS, and TYPEDEFS //! \name ENUMS, EXCEPTIONS, and TYPEDEFS
@ -236,8 +236,13 @@ private:
SecWordBlock reg; SecWordBlock reg;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<PolynomialMod2>;
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing<PolynomialMod2>;
CRYPTOPP_DLL_TEMPLATE_CLASS EuclideanDomainOf<PolynomialMod2>;
CRYPTOPP_DLL_TEMPLATE_CLASS QuotientRing<EuclideanDomainOf<PolynomialMod2> >;
//! GF(2^n) with Polynomial Basis //! GF(2^n) with Polynomial Basis
class GF2NP : public QuotientRing<EuclideanDomainOf<PolynomialMod2> > class CRYPTOPP_DLL GF2NP : public QuotientRing<EuclideanDomainOf<PolynomialMod2> >
{ {
public: public:
GF2NP(const PolynomialMod2 &modulus); GF2NP(const PolynomialMod2 &modulus);
@ -273,7 +278,7 @@ protected:
}; };
//! GF(2^n) with Trinomial Basis //! GF(2^n) with Trinomial Basis
class GF2NT : public GF2NP class CRYPTOPP_DLL GF2NT : public GF2NP
{ {
public: public:
// polynomial modulus = x^t0 + x^t1 + x^t2, t0 > t1 > t2 // polynomial modulus = x^t0 + x^t1 + x^t2, t0 > t1 > t2
@ -297,7 +302,7 @@ private:
}; };
//! GF(2^n) with Pentanomial Basis //! GF(2^n) with Pentanomial Basis
class GF2NPP : public GF2NP class CRYPTOPP_DLL GF2NPP : public GF2NP
{ {
public: public:
// polynomial modulus = x^t0 + x^t1 + x^t2 + x^t3 + x^t4, t0 > t1 > t2 > t3 > t4 // 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 // 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) inline bool operator==(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b)

View File

@ -1,6 +1,9 @@
// dsa.cpp - written and placed in the public domain by Wei Dai // dsa.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "gfpcrypt.h" #include "gfpcrypt.h"
#include "asn.h" #include "asn.h"
#include "oids.h" #include "oids.h"
@ -265,3 +268,5 @@ unsigned int DL_GroupParameters_IntegerBased::GetDefaultSubgroupOrderSize(unsign
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -17,8 +17,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters<Integer>;
//! . //! .
class CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public DL_GroupParameters<Integer>, public ASN1CryptoMaterial class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public DL_GroupParameters<Integer>, public ASN1CryptoMaterial
{ {
typedef DL_GroupParameters_IntegerBased ThisClass; typedef DL_GroupParameters_IntegerBased ThisClass;
@ -110,8 +112,10 @@ public:
{return !operator==(rhs);} {return !operator==(rhs);}
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>;
//! . //! .
class DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation> class CRYPTOPP_DLL DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>
{ {
public: public:
// DL_GroupParameters // 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: public:
typedef NoCofactorMultiplication DefaultCofactorOption; typedef NoCofactorMultiplication DefaultCofactorOption;
@ -172,6 +176,8 @@ public:
} }
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_GDSA<Integer>;
//! . //! .
template <class T> template <class T>
class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm<T> class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm<T>
@ -179,11 +185,6 @@ class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm<T>
public: public:
static const char * StaticAlgorithmName() {return "NR";} 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<T> &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const void Sign(const DL_GroupParameters<T> &params, const Integer &x, const Integer &k, const Integer &e, Integer &r, Integer &s) const
{ {
const Integer &q = params.GetSubgroupOrder(); 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: public:
/*! also checks that the lengths of p and q are allowed by the DSA standard */ /*! also checks that the lengths of p and q are allowed by the DSA standard */
@ -371,6 +372,10 @@ public:
struct DSA; struct DSA;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_GFP<DL_GroupParameters_DSA>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_GFP<DL_GroupParameters_DSA>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_GFP<DL_GroupParameters_DSA>, DSA>;
//! . //! .
struct DL_Keys_DSA struct DL_Keys_DSA
{ {
@ -379,7 +384,7 @@ struct DL_Keys_DSA
}; };
//! <a href="http://www.weidai.com/scan-mirror/sig.html#DSA">DSA</a> //! <a href="http://www.weidai.com/scan-mirror/sig.html#DSA">DSA</a>
struct DSA : public DL_SS< struct CRYPTOPP_DLL DSA : public DL_SS<
DL_Keys_DSA, DL_Keys_DSA,
DL_Algorithm_GDSA<Integer>, DL_Algorithm_GDSA<Integer>,
DL_SignatureMessageEncodingMethod_DSA, DL_SignatureMessageEncodingMethod_DSA,

6
gost.h
View File

@ -17,7 +17,7 @@ struct GOST_Info : public FixedBlockSize<8>, public FixedKeyLength<32>
/// <a href="http://www.weidai.com/scan-mirror/cs.html#GOST">GOST</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#GOST">GOST</a>
class GOST : public GOST_Info, public BlockCipherDocumentation class GOST : public GOST_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<GOST_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<GOST_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length);
@ -45,8 +45,8 @@ class GOST : public GOST_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
typedef GOST::Encryption GOSTEncryption; typedef GOST::Encryption GOSTEncryption;

View File

@ -7,9 +7,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
HAVAL::HAVAL(unsigned int digestSize, unsigned int pass) HAVAL::HAVAL(unsigned int digestSize, unsigned int pass)
: IteratedHash<word32, LittleEndian, 128>(DIGESTSIZE) : digestSize(digestSize), pass(pass)
, digestSize(digestSize), pass(pass)
{ {
SetStateSize(DIGESTSIZE);
if (!(digestSize >= 16 && digestSize <= 32 && digestSize%4==0)) if (!(digestSize >= 16 && digestSize <= 32 && digestSize%4==0))
throw InvalidArgument("HAVAL: invalid digest size"); throw InvalidArgument("HAVAL: invalid digest size");
@ -31,7 +32,7 @@ void HAVAL::Init()
m_digest[7] = 0xEC4E6C89; m_digest[7] = 0xEC4E6C89;
} }
void HAVAL::vTransform(const word32 *in) void HAVAL::HashEndianCorrectedBlock(const word32 *in)
{ {
if (pass==3) if (pass==3)
HAVAL3::Transform(m_digest, in); HAVAL3::Transform(m_digest, in);
@ -53,7 +54,7 @@ void HAVAL::TruncatedFinal(byte *hash, unsigned int size)
m_data[30] = GetBitCountLo(); m_data[30] = GetBitCountLo();
m_data[31] = GetBitCountHi(); m_data[31] = GetBitCountHi();
vTransform(m_data); HashEndianCorrectedBlock(m_data);
Tailor(digestSize*8); Tailor(digestSize*8);
CorrectEndianess(m_digest, m_digest, digestSize); CorrectEndianess(m_digest, m_digest, digestSize);
memcpy(hash, m_digest, size); memcpy(hash, m_digest, size);

View File

@ -23,7 +23,7 @@ protected:
void Init(); void Init();
void Tailor(unsigned int FPTLEN); void Tailor(unsigned int FPTLEN);
void vTransform(const word32 *in); void HashEndianCorrectedBlock(const word32 *in);
const unsigned int digestSize, pass; const unsigned int digestSize, pass;
}; };

View File

@ -1,6 +1,9 @@
// hex.cpp - written and placed in the public domain by Wei Dai // hex.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "hex.h" #include "hex.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -30,3 +33,5 @@ const int *HexDecoder::GetDecodingLookupArray()
} }
NAMESPACE_END NAMESPACE_END
#endif

4
hex.h
View File

@ -6,7 +6,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! Converts given data to base 16 //! Converts given data to base 16
class HexEncoder : public SimpleProxyFilter class CRYPTOPP_DLL HexEncoder : public SimpleProxyFilter
{ {
public: public:
HexEncoder(BufferedTransformation *attachment = NULL, bool uppercase = true, int outputGroupSize = 0, const std::string &separator = ":", const std::string &terminator = "") 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 //! Decode base 16 data back to bytes
class HexDecoder : public BaseN_Decoder class CRYPTOPP_DLL HexDecoder : public BaseN_Decoder
{ {
public: public:
HexDecoder(BufferedTransformation *attachment = NULL) HexDecoder(BufferedTransformation *attachment = NULL)

84
hmac.cpp Normal file
View File

@ -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<blockSize; i++)
{
AccessOpad()[i] = AccessIpad()[i] ^ OPAD;
AccessIpad()[i] ^= IPAD;
}
}
void HMAC_Base::KeyInnerHash()
{
assert(!m_innerHashKeyed);
HashTransformation &hash = AccessHash();
hash.Update(AccessIpad(), hash.BlockSize());
m_innerHashKeyed = true;
}
void HMAC_Base::Restart()
{
if (m_innerHashKeyed)
{
AccessHash().Restart();
m_innerHashKeyed = false;
}
}
void HMAC_Base::Update(const byte *input, unsigned int length)
{
if (!m_innerHashKeyed)
KeyInnerHash();
AccessHash().Update(input, length);
}
void HMAC_Base::TruncatedFinal(byte *mac, unsigned int size)
{
ThrowIfInvalidTruncatedSize(size);
HashTransformation &hash = AccessHash();
if (!m_innerHashKeyed)
KeyInnerHash();
hash.Final(AccessInnerHash());
hash.Update(AccessOpad(), hash.BlockSize());
hash.Update(AccessInnerHash(), hash.DigestSize());
hash.TruncatedFinal(mac, size);
m_innerHashKeyed = false;
}
NAMESPACE_END
#endif

105
hmac.h
View File

@ -8,112 +8,57 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
template <class T> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HMAC_Base : public VariableKeyLength<16, 0, UINT_MAX>, public MessageAuthenticationCode
class CRYPTOPP_NO_VTABLE HMAC_Base : public VariableKeyLength<16, 0, UINT_MAX>, public MessageAuthenticationCode
{ {
public: 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) {} HMAC_Base() : m_innerHashKeyed(false) {}
void UncheckedSetKey(const byte *userKey, unsigned int keylength); void UncheckedSetKey(const byte *userKey, unsigned int keylength);
void Restart(); void Restart();
void Update(const byte *input, unsigned int length); void Update(const byte *input, unsigned int length);
void TruncatedFinal(byte *mac, unsigned int size); void TruncatedFinal(byte *mac, unsigned int size);
unsigned int DigestSize() const {return DIGESTSIZE;} unsigned int OptimalBlockSize() const {return const_cast<HMAC_Base*>(this)->AccessHash().OptimalBlockSize();}
unsigned int DigestSize() const {return const_cast<HMAC_Base*>(this)->AccessHash().DigestSize();}
protected:
virtual HashTransformation & AccessHash() =0;
virtual byte * AccessIpad() =0;
virtual byte * AccessOpad() =0;
virtual byte * AccessInnerHash() =0;
private: private:
void KeyInnerHash(); void KeyInnerHash();
enum {IPAD=0x36, OPAD=0x5c}; enum {IPAD=0x36, OPAD=0x5c};
FixedSizeSecBlock<byte, BLOCKSIZE> k_ipad, k_opad;
FixedSizeSecBlock<byte, DIGESTSIZE> m_innerHash;
T m_hash;
bool m_innerHashKeyed; bool m_innerHashKeyed;
}; };
//! <a href="http://www.weidai.com/scan-mirror/mac.html#HMAC">HMAC</a> //! <a href="http://www.weidai.com/scan-mirror/mac.html#HMAC">HMAC</a>
/*! HMAC(K, text) = H(K XOR opad, H(K XOR ipad, text)) */ /*! HMAC(K, text) = H(K XOR opad, H(K XOR ipad, text)) */
template <class T> template <class T>
class HMAC : public MessageAuthenticationCodeTemplate<HMAC_Base<T> > class HMAC : public MessageAuthenticationCodeImpl<HMAC_Base, HMAC<T> >
{ {
public: public:
enum {DIGESTSIZE=T::DIGESTSIZE, BLOCKSIZE=T::BLOCKSIZE};
HMAC() {} HMAC() {}
HMAC(const byte *key, unsigned int length=HMAC_Base<T>::DEFAULT_KEYLENGTH) HMAC(const byte *key, unsigned int length=HMAC_Base::DEFAULT_KEYLENGTH)
{SetKey(key, length);} {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<byte, BLOCKSIZE> m_ipad, m_opad;
FixedSizeSecBlock<byte, DIGESTSIZE> m_innerHash;
T m_hash;
}; };
template <class T>
void HMAC_Base<T>::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<T::BLOCKSIZE; i++)
{
k_opad[i] = k_ipad[i] ^ OPAD;
k_ipad[i] ^= IPAD;
}
}
template <class T>
void HMAC_Base<T>::KeyInnerHash()
{
assert(!m_innerHashKeyed);
m_hash.Update(k_ipad, T::BLOCKSIZE);
m_innerHashKeyed = true;
}
template <class T>
void HMAC_Base<T>::Restart()
{
if (m_innerHashKeyed)
{
m_hash.Restart();
m_innerHashKeyed = false;
}
}
template <class T>
void HMAC_Base<T>::Update(const byte *input, unsigned int length)
{
if (!m_innerHashKeyed)
KeyInnerHash();
m_hash.Update(input, length);
}
template <class T>
void HMAC_Base<T>::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 NAMESPACE_END
#endif #endif

6
idea.h
View File

@ -17,7 +17,7 @@ struct IDEA_Info : public FixedBlockSize<8>, public FixedKeyLength<16>, public F
/// <a href="http://www.weidai.com/scan-mirror/cs.html#IDEA">IDEA</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#IDEA">IDEA</a>
class IDEA : public IDEA_Info, public BlockCipherDocumentation class IDEA : public IDEA_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<IDEA_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<IDEA_Info>
{ {
public: public:
unsigned int GetAlignment() const {return 2;} unsigned int GetAlignment() const {return 2;}
@ -40,8 +40,8 @@ class IDEA : public IDEA_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
typedef IDEA::Encryption IDEAEncryption; typedef IDEA::Encryption IDEAEncryption;

View File

@ -2,6 +2,9 @@
// contains public domain code contributed by Alister Lee and Leonard Janke // contains public domain code contributed by Alister Lee and Leonard Janke
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "integer.h" #include "integer.h"
#include "modarith.h" #include "modarith.h"
#include "nbtheory.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.") #pragma message("You do no seem to have the Visual C++ Processor Pack installed, so use of SSE2 intrinsics will be disabled.")
#endif #endif
#include "algebra.cpp"
#include "eprecomp.cpp"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
bool FunctionAssignIntToInteger(const std::type_info &valueType, void *pInteger, const void *pInt) bool FunctionAssignIntToInteger(const std::type_info &valueType, void *pInteger, const void *pInt)
@ -58,8 +58,6 @@ void AlignedAllocator<T>::deallocate(void *p, size_type n)
#endif #endif
delete [] p; delete [] p;
} }
template class AlignedAllocator<word>;
#endif #endif
#define MAKE_DWORD(lowWord, highWord) ((dword(highWord)<<WORD_BITS) | (lowWord)) #define MAKE_DWORD(lowWord, highWord) ((dword(highWord)<<WORD_BITS) | (lowWord))
@ -752,6 +750,11 @@ static bool GetSSE2Capability()
bool g_sse2DetectionDone = false, g_sse2Detected, g_sse2Enabled = true; bool g_sse2DetectionDone = false, g_sse2Detected, g_sse2Enabled = true;
void DisableSSE2()
{
g_sse2Enabled = false;
}
static inline bool HasSSE2() static inline bool HasSSE2()
{ {
if (g_sse2Enabled && !g_sse2DetectionDone) if (g_sse2Enabled && !g_sse2DetectionDone)
@ -4001,6 +4004,6 @@ const Integer& MontgomeryRepresentation::MultiplicativeInverse(const Integer &a)
return result; return result;
} }
template class AbstractRing<Integer>;
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -24,6 +24,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
#if defined(SSE2_INTRINSICS_AVAILABLE) || defined(_MSC_VER) #if defined(SSE2_INTRINSICS_AVAILABLE) || defined(_MSC_VER)
template <class T> template <class T>
class AlignedAllocator : public AllocatorBase<T> class AlignedAllocator : public AllocatorBase<T>
{ {
@ -37,7 +38,11 @@ NAMESPACE_BEGIN(CryptoPP)
return StandardReallocate(*this, p, oldSize, newSize, preserve); return StandardReallocate(*this, p, oldSize, newSize, preserve);
} }
}; };
template class CRYPTOPP_DLL AlignedAllocator<word>;
typedef SecBlock<word, AlignedAllocator<word> > SecAlignedWordBlock; typedef SecBlock<word, AlignedAllocator<word> > SecAlignedWordBlock;
void CRYPTOPP_DLL DisableSSE2();
#else #else
typedef SecWordBlock SecAlignedWordBlock; typedef SecWordBlock SecAlignedWordBlock;
#endif #endif
@ -47,7 +52,7 @@ NAMESPACE_BEGIN(CryptoPP)
with absolute value less than (256**sizeof(word)) ** (256**sizeof(int)). with absolute value less than (256**sizeof(word)) ** (256**sizeof(int)).
\nosubgrouping \nosubgrouping
*/ */
class Integer : public ASN1Object class CRYPTOPP_DLL Integer : public ASN1Object
{ {
public: public:
//! \name ENUMS, EXCEPTIONS, and TYPEDEFS //! \name ENUMS, EXCEPTIONS, and TYPEDEFS
@ -355,9 +360,9 @@ public:
Integer MultiplicativeInverse() const; Integer MultiplicativeInverse() const;
//! modular multiplication //! 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 //! 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)) //! 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); static void Divide(Integer &r, Integer &q, const Integer &a, const Integer &d);
@ -378,9 +383,9 @@ public:
//! \name INPUT/OUTPUT //! \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: private:

View File

@ -1,18 +1,14 @@
// iterhash.cpp - written and placed in the public domain by Wei Dai // iterhash.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "iterhash.h" #include "iterhash.h"
#include "misc.h" #include "misc.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
template <class T, class BASE>
IteratedHashBase<T, BASE>::IteratedHashBase(unsigned int blockSize, unsigned int digestSize)
: m_data(blockSize/sizeof(T)), m_digest(digestSize/sizeof(T))
, m_countHi(0), m_countLo(0)
{
}
template <class T, class BASE> void IteratedHashBase<T, BASE>::Update(const byte *input, unsigned int len) template <class T, class BASE> void IteratedHashBase<T, BASE>::Update(const byte *input, unsigned int len)
{ {
HashWordType tmp = m_countLo; HashWordType tmp = m_countLo;
@ -111,12 +107,6 @@ template <class T, class BASE> void IteratedHashBase<T, BASE>::Restart()
Init(); Init();
} }
#ifdef WORD64_AVAILABLE
template class IteratedHashBase<word64, HashTransformation>;
template class IteratedHashBase<word64, MessageAuthenticationCode>;
#endif
template class IteratedHashBase<word32, HashTransformation>;
template class IteratedHashBase<word32, MessageAuthenticationCode>;
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -4,6 +4,7 @@
#include "cryptlib.h" #include "cryptlib.h"
#include "secblock.h" #include "secblock.h"
#include "misc.h" #include "misc.h"
#include "simple.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -13,8 +14,10 @@ class CRYPTOPP_NO_VTABLE IteratedHashBase : public BASE
public: public:
typedef T HashWordType; typedef T HashWordType;
IteratedHashBase(unsigned int blockSize, unsigned int digestSize); IteratedHashBase() : m_countHi(0), m_countLo(0) {}
unsigned int DigestSize() const {return m_digest.size() * sizeof(T);}; 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 OptimalBlockSize() const {return BlockSize();}
unsigned int OptimalDataAlignment() const {return sizeof(T);} unsigned int OptimalDataAlignment() const {return sizeof(T);}
void Update(const byte *input, unsigned int length); void Update(const byte *input, unsigned int length);
@ -29,7 +32,6 @@ protected:
void PadLastBlock(unsigned int lastBlockSize, byte padFirst=0x80); void PadLastBlock(unsigned int lastBlockSize, byte padFirst=0x80);
virtual void Init() =0; virtual void Init() =0;
virtual void HashBlock(const T *input) =0; virtual void HashBlock(const T *input) =0;
virtual unsigned int BlockSize() const =0;
SecBlock<T> m_data; // Data buffer SecBlock<T> m_data; // Data buffer
SecBlock<T> m_digest; // Message digest SecBlock<T> m_digest; // Message digest
@ -38,14 +40,19 @@ private:
T m_countLo, m_countHi; T m_countLo, m_countHi;
}; };
#ifdef WORD64_AVAILABLE
CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase<word64, HashTransformation>;
CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase<word64, MessageAuthenticationCode>;
#endif
CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase<word32, HashTransformation>;
CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase<word32, MessageAuthenticationCode>;
//! . //! .
template <class T, class B, class BASE> template <class T, class B, class BASE>
class CRYPTOPP_NO_VTABLE IteratedHashBase2 : public IteratedHashBase<T, BASE> class CRYPTOPP_NO_VTABLE IteratedHashBase2 : public IteratedHashBase<T, BASE>
{ {
public: public:
IteratedHashBase2(unsigned int blockSize, unsigned int digestSize)
: IteratedHashBase<T, BASE>(blockSize, digestSize) {}
typedef B ByteOrderClass; typedef B ByteOrderClass;
typedef typename IteratedHashBase<T, BASE>::HashWordType HashWordType; typedef typename IteratedHashBase<T, BASE>::HashWordType HashWordType;
@ -58,32 +65,37 @@ public:
protected: protected:
void HashBlock(const HashWordType *input); void HashBlock(const HashWordType *input);
virtual void HashEndianCorrectedBlock(const HashWordType *data) =0;
virtual void vTransform(const HashWordType *data) =0;
}; };
//! . //! .
template <class T, class B, unsigned int S, class BASE = HashTransformation> template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, class T_Base = HashTransformation>
class CRYPTOPP_NO_VTABLE IteratedHash : public IteratedHashBase2<T, B, BASE> class CRYPTOPP_NO_VTABLE IteratedHash : public IteratedHashBase2<T_HashWordType, T_Endianness, T_Base>
{ {
public: public:
enum {BLOCKSIZE = S}; enum {BLOCKSIZE = T_BlockSize};
private:
CRYPTOPP_COMPILE_ASSERT((BLOCKSIZE & (BLOCKSIZE - 1)) == 0); // blockSize is a power of 2 CRYPTOPP_COMPILE_ASSERT((BLOCKSIZE & (BLOCKSIZE - 1)) == 0); // blockSize is a power of 2
protected: protected:
IteratedHash(unsigned int digestSize) : IteratedHashBase2<T, B, BASE>(BLOCKSIZE, digestSize) {} IteratedHash() {SetBlockSize(T_BlockSize);}
unsigned int BlockSize() const {return BLOCKSIZE;}
}; };
template <class T, class B, unsigned int S, class M> template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, unsigned int T_StateSize, class T_Transform, unsigned int T_DigestSize = T_StateSize>
class CRYPTOPP_NO_VTABLE IteratedHashWithStaticTransform : public IteratedHash<T, B, S> class CRYPTOPP_NO_VTABLE IteratedHashWithStaticTransform
: public ClonableImpl<T_Transform, AlgorithmImpl<IteratedHash<T_HashWordType, T_Endianness, T_BlockSize>, T_Transform> >
{ {
public:
enum {DIGESTSIZE = T_DigestSize};
unsigned int DigestSize() const {return DIGESTSIZE;};
protected: protected:
IteratedHashWithStaticTransform(unsigned int digestSize) : IteratedHash<T, B, S>(digestSize) {} IteratedHashWithStaticTransform()
void vTransform(const T *data) {M::Transform(m_digest, data);} {
std::string AlgorithmName() const {return M::StaticAlgorithmName();} 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 <class T, class B, class BASE> void IteratedHashBase2<T, B, BASE>::Trun
m_data[m_data.size()-2] = B::ToEnum() ? GetBitCountHi() : GetBitCountLo(); m_data[m_data.size()-2] = B::ToEnum() ? GetBitCountHi() : GetBitCountLo();
m_data[m_data.size()-1] = B::ToEnum() ? GetBitCountLo() : GetBitCountHi(); m_data[m_data.size()-1] = B::ToEnum() ? GetBitCountLo() : GetBitCountHi();
vTransform(m_data); HashEndianCorrectedBlock(m_data);
CorrectEndianess(m_digest, m_digest, DigestSize()); CorrectEndianess(m_digest, m_digest, DigestSize());
memcpy(hash, m_digest, size); memcpy(hash, m_digest, size);
@ -108,11 +120,11 @@ template <class T, class B, class BASE> void IteratedHashBase2<T, B, BASE>::Trun
template <class T, class B, class BASE> void IteratedHashBase2<T, B, BASE>::HashBlock(const HashWordType *input) template <class T, class B, class BASE> void IteratedHashBase2<T, B, BASE>::HashBlock(const HashWordType *input)
{ {
if (NativeByteOrderIs(B::ToEnum())) if (NativeByteOrderIs(B::ToEnum()))
vTransform(input); HashEndianCorrectedBlock(input);
else else
{ {
ByteReverse(m_data.begin(), input, BlockSize()); ByteReverse(m_data.begin(), input, BlockSize());
vTransform(m_data); HashEndianCorrectedBlock(m_data);
} }
} }

View File

@ -23,7 +23,7 @@ struct LR_Info : public VariableKeyLength<16, 0, 2*(UINT_MAX/2), 2>, public Fixe
template <class T> template <class T>
class LR : public LR_Info<T>, public BlockCipherDocumentation class LR : public LR_Info<T>, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<LR_Info<T> > class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<LR_Info<T> >
{ {
public: public:
// VC60 workaround: have to define these functions within class definition // VC60 workaround: have to define these functions within class definition
@ -129,8 +129,8 @@ class LR : public LR_Info<T>, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
NAMESPACE_END NAMESPACE_END

View File

@ -7,8 +7,6 @@
#include "sha.h" #include "sha.h"
#include "algparam.h" #include "algparam.h"
#include "oaep.cpp"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
void LUC_TestInstantiations() void LUC_TestInstantiations()

6
mars.h
View File

@ -17,7 +17,7 @@ struct MARS_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 5
/// <a href="http://www.weidai.com/scan-mirror/cs.html#MARS">MARS</a> /// <a href="http://www.weidai.com/scan-mirror/cs.html#MARS">MARS</a>
class MARS : public MARS_Info, public BlockCipherDocumentation class MARS : public MARS_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherBaseTemplate<MARS_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<MARS_Info>
{ {
public: public:
void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length); void UncheckedSetKey(CipherDir direction, const byte *userKey, unsigned int length);
@ -41,8 +41,8 @@ class MARS : public MARS_Info, public BlockCipherDocumentation
}; };
public: public:
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
typedef BlockCipherTemplate<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
typedef MARS::Encryption MARSEncryption; typedef MARS::Encryption MARSEncryption;

10
md4.cpp
View File

@ -20,12 +20,12 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
void MD4::Init() void MD4::InitState(HashWordType *state)
{ {
m_digest[0] = 0x67452301L; state[0] = 0x67452301L;
m_digest[1] = 0xefcdab89L; state[1] = 0xefcdab89L;
m_digest[2] = 0x98badcfeL; state[2] = 0x98badcfeL;
m_digest[3] = 0x10325476L; state[3] = 0x10325476L;
} }
void MD4::Transform (word32 *digest, const word32 *in) void MD4::Transform (word32 *digest, const word32 *in)

8
md4.h
View File

@ -8,16 +8,12 @@ NAMESPACE_BEGIN(CryptoPP)
//! <a href="http://www.weidai.com/scan-mirror/md.html#MD4">MD4</a> //! <a href="http://www.weidai.com/scan-mirror/md.html#MD4">MD4</a>
/*! \warning MD4 is considered insecure, and should not be used /*! \warning MD4 is considered insecure, and should not be used
unless you absolutely need compatibility with a broken product. */ unless you absolutely need compatibility with a broken product. */
class MD4 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, MD4> class MD4 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, 16, MD4>
{ {
public: public:
enum {DIGESTSIZE = 16}; static void InitState(HashWordType *state);
MD4() : IteratedHashWithStaticTransform<word32, LittleEndian, 64, MD4>(DIGESTSIZE) {Init();}
static void Transform(word32 *digest, const word32 *data); static void Transform(word32 *digest, const word32 *data);
static const char *StaticAlgorithmName() {return "MD4";} static const char *StaticAlgorithmName() {return "MD4";}
protected:
void Init();
}; };
NAMESPACE_END NAMESPACE_END

10
md5.cpp
View File

@ -12,12 +12,12 @@ void MD5_TestInstantiations()
MD5 x; MD5 x;
} }
void MD5::Init() void MD5::InitState(HashWordType *state)
{ {
m_digest[0] = 0x67452301L; state[0] = 0x67452301L;
m_digest[1] = 0xefcdab89L; state[1] = 0xefcdab89L;
m_digest[2] = 0x98badcfeL; state[2] = 0x98badcfeL;
m_digest[3] = 0x10325476L; state[3] = 0x10325476L;
} }
void MD5::Transform (word32 *digest, const word32 *in) void MD5::Transform (word32 *digest, const word32 *in)

8
md5.h
View File

@ -7,16 +7,12 @@ NAMESPACE_BEGIN(CryptoPP)
//! <a href="http://www.weidai.com/scan-mirror/md.html#MD5">MD5</a> //! <a href="http://www.weidai.com/scan-mirror/md.html#MD5">MD5</a>
/*! 128 Bit Hash */ /*! 128 Bit Hash */
class MD5 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, MD5> class MD5 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, 16, MD5>
{ {
public: public:
enum {DIGESTSIZE = 16}; static void InitState(HashWordType *state);
MD5() : IteratedHashWithStaticTransform<word32, LittleEndian, 64, MD5>(DIGESTSIZE) {Init();}
static void Transform(word32 *digest, const word32 *data); static void Transform(word32 *digest, const word32 *data);
static const char * StaticAlgorithmName() {return "MD5";} static const char * StaticAlgorithmName() {return "MD5";}
protected:
void Init();
}; };
NAMESPACE_END NAMESPACE_END

View File

@ -16,14 +16,15 @@ public:
static std::string StaticAlgorithmName() {return "MD5-MAC";} static std::string StaticAlgorithmName() {return "MD5-MAC";}
enum {DIGESTSIZE = 16}; enum {DIGESTSIZE = 16};
MD5MAC_Base() : IteratedHash<word32, LittleEndian, 64, MessageAuthenticationCode>(DIGESTSIZE) {} MD5MAC_Base() {SetStateSize(DIGESTSIZE);}
void UncheckedSetKey(const byte *userKey, unsigned int keylength); void UncheckedSetKey(const byte *userKey, unsigned int keylength);
void TruncatedFinal(byte *mac, unsigned int size); void TruncatedFinal(byte *mac, unsigned int size);
unsigned int DigestSize() const {return DIGESTSIZE;}
protected: protected:
static void Transform (word32 *buf, const word32 *in, const word32 *key); 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(); void Init();
static const word32 T[12]; static const word32 T[12];
@ -31,7 +32,7 @@ protected:
}; };
//! <a href="http://www.weidai.com/scan-mirror/mac.html#MD5-MAC">MD5-MAC</a> //! <a href="http://www.weidai.com/scan-mirror/mac.html#MD5-MAC">MD5-MAC</a>
typedef MessageAuthenticationCodeTemplate<MD5MAC_Base> MD5MAC; typedef MessageAuthenticationCodeFinal<MD5MAC_Base> MD5MAC;
NAMESPACE_END NAMESPACE_END

4
mdc.h
View File

@ -22,7 +22,7 @@ struct MDC_Info : public FixedBlockSize<T::DIGESTSIZE>, public FixedKeyLength<T:
template <class T> template <class T>
class MDC : public MDC_Info<T> class MDC : public MDC_Info<T>
{ {
class CRYPTOPP_NO_VTABLE Enc : public BlockCipherBaseTemplate<MDC_Info<T> > class CRYPTOPP_NO_VTABLE Enc : public BlockCipherImpl<MDC_Info<T> >
{ {
typedef typename T::HashWordType HashWordType; typedef typename T::HashWordType HashWordType;
@ -64,7 +64,7 @@ class MDC : public MDC_Info<T>
public: public:
//! use BlockCipher interface //! use BlockCipher interface
typedef BlockCipherTemplate<ENCRYPTION, Enc> Encryption; typedef BlockCipherFinal<ENCRYPTION, Enc> Encryption;
}; };
NAMESPACE_END NAMESPACE_END

View File

@ -1,19 +1,14 @@
// misc.cpp - written and placed in the public domain by Wei Dai // misc.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "misc.h" #include "misc.h"
#include "words.h" #include "words.h"
NAMESPACE_BEGIN(CryptoPP) 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) void xorbuf(byte *buf, const byte *mask, unsigned int count)
{ {
if (((unsigned int)buf | (unsigned int)mask | count) % WORD_SIZE == 0) 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 NAMESPACE_END
#endif

23
misc.h
View File

@ -1,12 +1,7 @@
#ifndef CRYPTOPP_MISC_H #ifndef CRYPTOPP_MISC_H
#define CRYPTOPP_MISC_H #define CRYPTOPP_MISC_H
#include "config.h"
#include "cryptlib.h" #include "cryptlib.h"
#include <assert.h>
#include <string.h> // CodeWarrior doesn't have memory.h
#include <algorithm>
#include <string>
#ifdef INTEL_INTRINSICS #ifdef INTEL_INTRINSICS
#include <stdlib.h> #include <stdlib.h>
@ -23,13 +18,17 @@ struct CompileAssert
}; };
#define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__) #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) #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_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y)
#define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y #define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y
// ************** misc classes *************** // ************** misc classes ***************
class Empty class CRYPTOPP_DLL Empty
{ {
}; };
@ -80,10 +79,10 @@ template <class _Tp> inline const _Tp& STDMAX(const _Tp& __a, const _Tp& __b)
// #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255) // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
// #define GETBYTE(x, y) (((byte *)&(x))[y]) // #define GETBYTE(x, y) (((byte *)&(x))[y])
unsigned int Parity(unsigned long); CRYPTOPP_DLL unsigned int Parity(unsigned long);
unsigned int BytePrecision(unsigned long); CRYPTOPP_DLL unsigned int BytePrecision(unsigned long);
unsigned int BitPrecision(unsigned long); CRYPTOPP_DLL unsigned int BitPrecision(unsigned long);
unsigned long Crop(unsigned long, unsigned int size); CRYPTOPP_DLL unsigned long Crop(unsigned long, unsigned int size);
inline unsigned int BitsToBytes(unsigned int bitCount) 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)); return ((bitCount+WORD_BITS-1)/(WORD_BITS));
} }
void xorbuf(byte *buf, const byte *mask, unsigned int count); CRYPTOPP_DLL 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 *output, const byte *input, const byte *mask, unsigned int count);
template <class T> template <class T>
inline bool IsPowerOf2(T n) inline bool IsPowerOf2(T n)

View File

@ -10,8 +10,12 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<Integer>;
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing<Integer>;
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractEuclideanDomain<Integer>;
//! . //! .
class ModularArithmetic : public AbstractRing<Integer> class CRYPTOPP_DLL ModularArithmetic : public AbstractRing<Integer>
{ {
public: public:
@ -99,6 +103,9 @@ public:
return Element( rng , Integer( (long) 0) , modulus - Integer( (long) 1 ) ) ; return Element( rng , Integer( (long) 0) , modulus - Integer( (long) 1 ) ) ;
} }
bool operator==(const ModularArithmetic &rhs) const
{return modulus == rhs.modulus;}
static const RandomizationParameter DefaultRandomizationParameter ; static const RandomizationParameter DefaultRandomizationParameter ;
protected: protected:
@ -110,7 +117,7 @@ protected:
// const ModularArithmetic::RandomizationParameter ModularArithmetic::DefaultRandomizationParameter = 0 ; // const ModularArithmetic::RandomizationParameter ModularArithmetic::DefaultRandomizationParameter = 0 ;
//! do modular arithmetics in Montgomery representation for increased speed //! do modular arithmetics in Montgomery representation for increased speed
class MontgomeryRepresentation : public ModularArithmetic class CRYPTOPP_DLL MontgomeryRepresentation : public ModularArithmetic
{ {
public: public:
MontgomeryRepresentation(const Integer &modulus); // modulus must be odd MontgomeryRepresentation(const Integer &modulus); // modulus must be odd

View File

@ -1,14 +1,18 @@
// modes.cpp - written and placed in the public domain by Wei Dai // modes.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "modes.h" #include "modes.h"
#ifndef NDEBUG
#include "des.h" #include "des.h"
#endif
#include "strciphr.cpp"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
#ifndef NDEBUG
void Modes_TestInstantiations() void Modes_TestInstantiations()
{ {
CFB_Mode<DES>::Encryption m0; CFB_Mode<DES>::Encryption m0;
@ -18,17 +22,7 @@ void Modes_TestInstantiations()
ECB_Mode<DES>::Encryption m4; ECB_Mode<DES>::Encryption m4;
CBC_Mode<DES>::Encryption m5; CBC_Mode<DES>::Encryption m5;
} }
#endif
// explicit instantiations for Darwin gcc-932.1
template class CFB_CipherTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, SymmetricCipher> >;
template class CFB_EncryptionTemplate<>;
template class CFB_DecryptionTemplate<>;
template class AdditiveCipherTemplate<>;
template class CFB_CipherTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
template class CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
template class CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
template class AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> >;
template class AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> >;
void CipherModeBase::SetKey(const byte *key, unsigned int length, const NameValuePairs &params) void CipherModeBase::SetKey(const byte *key, unsigned int length, const NameValuePairs &params)
{ {
@ -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) static inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int s)
{ {
for (int i=s-1, carry=1; i>=0; i--) int i, carry;
carry = !(output[i] = input[i]+carry) && 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) 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 NAMESPACE_END
#endif

83
modes.h
View File

@ -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: public:
unsigned int MinKeyLength() const {return m_cipher->MinKeyLength();} unsigned int MinKeyLength() const {return m_cipher->MinKeyLength();}
@ -66,16 +66,19 @@ template <class POLICY_INTERFACE>
class CRYPTOPP_NO_VTABLE ModePolicyCommonTemplate : public CipherModeBase, public POLICY_INTERFACE class CRYPTOPP_NO_VTABLE ModePolicyCommonTemplate : public CipherModeBase, public POLICY_INTERFACE
{ {
unsigned int GetAlignment() const {return m_cipher->BlockAlignment();} unsigned int GetAlignment() const {return m_cipher->BlockAlignment();}
void CipherSetKey(const NameValuePairs &params, const byte *key, unsigned int length) void CipherSetKey(const NameValuePairs &params, const byte *key, unsigned int length);
{ };
template <class POLICY_INTERFACE>
void ModePolicyCommonTemplate<POLICY_INTERFACE>::CipherSetKey(const NameValuePairs &params, const byte *key, unsigned int length)
{
m_cipher->SetKey(key, length, params); m_cipher->SetKey(key, length, params);
ResizeBuffers(); ResizeBuffers();
int feedbackSize = params.GetIntValueWithDefault(Name::FeedbackSize(), 0); int feedbackSize = params.GetIntValueWithDefault(Name::FeedbackSize(), 0);
SetFeedbackSize(feedbackSize); SetFeedbackSize(feedbackSize);
} }
};
class CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate<CFB_CipherAbstractPolicy> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate<CFB_CipherAbstractPolicy>
{ {
public: public:
IV_Requirement IVRequirement() const {return RANDOM_IV;} 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); memset(dest, 0, s);
} }
class CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{ {
public:
bool IsRandomAccess() const {return false;}
IV_Requirement IVRequirement() const {return STRUCTURED_IV;}
private:
unsigned int GetBytesPerIteration() const {return BlockSize();} unsigned int GetBytesPerIteration() const {return BlockSize();}
unsigned int GetIterationsToBuffer() const {return 1;} unsigned int GetIterationsToBuffer() const {return 1;}
void WriteKeystream(byte *keystreamBuffer, unsigned int iterationCount) void WriteKeystream(byte *keystreamBuffer, unsigned int iterationCount)
{ {
assert(iterationCount == 1); assert(iterationCount == 1);
m_cipher->ProcessBlock(keystreamBuffer); m_cipher->ProcessBlock(keystreamBuffer);
memcpy(m_register, keystreamBuffer, BlockSize());
} }
void CipherResynchronize(byte *keystreamBuffer, const byte *iv) void CipherResynchronize(byte *keystreamBuffer, const byte *iv)
{ {
CopyOrZero(keystreamBuffer, iv, BlockSize()); CopyOrZero(keystreamBuffer, iv, BlockSize());
} }
bool IsRandomAccess() const {return false;}
IV_Requirement IVRequirement() const {return STRUCTURED_IV;}
}; };
class CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{ {
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 GetBytesPerIteration() const {return BlockSize();}
unsigned int GetIterationsToBuffer() const {return m_cipher->OptimalNumberOfParallelBlocks();} unsigned int GetIterationsToBuffer() const {return m_cipher->OptimalNumberOfParallelBlocks();}
void WriteKeystream(byte *buffer, unsigned int iterationCount) void WriteKeystream(byte *buffer, unsigned int iterationCount)
@ -144,16 +157,14 @@ class CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate<Additi
bool CanOperateKeystream() const {return true;} bool CanOperateKeystream() const {return true;}
void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, unsigned int iterationCount); void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, unsigned int iterationCount);
void CipherResynchronize(byte *keystreamBuffer, const byte *iv); void CipherResynchronize(byte *keystreamBuffer, const byte *iv);
bool IsRandomAccess() const {return true;}
void SeekToIteration(dword iterationCount); void SeekToIteration(dword iterationCount);
IV_Requirement IVRequirement() const {return STRUCTURED_IV;}
inline void ProcessMultipleBlocks(byte *output, const byte *input, unsigned int n); inline void ProcessMultipleBlocks(byte *output, const byte *input, unsigned int n);
SecByteBlock m_counterArray; SecByteBlock m_counterArray;
}; };
class CRYPTOPP_NO_VTABLE BlockOrientedCipherModeBase : public CipherModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockOrientedCipherModeBase : public CipherModeBase
{ {
public: public:
void UncheckedSetKey(const NameValuePairs &params, const byte *key, unsigned int length, const byte *iv); void UncheckedSetKey(const NameValuePairs &params, const byte *key, unsigned int length, const byte *iv);
@ -176,7 +187,7 @@ protected:
SecByteBlock m_buffer; SecByteBlock m_buffer;
}; };
class CRYPTOPP_NO_VTABLE ECB_OneWay : public BlockOrientedCipherModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ECB_OneWay : public BlockOrientedCipherModeBase
{ {
public: public:
IV_Requirement IVRequirement() const {return NOT_RESYNCHRONIZABLE;} IV_Requirement IVRequirement() const {return NOT_RESYNCHRONIZABLE;}
@ -185,7 +196,7 @@ public:
{m_cipher->ProcessAndXorMultipleBlocks(inString, NULL, outString, numberOfBlocks);} {m_cipher->ProcessAndXorMultipleBlocks(inString, NULL, outString, numberOfBlocks);}
}; };
class CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase
{ {
public: public:
IV_Requirement IVRequirement() const {return UNPREDICTABLE_RANDOM_IV;} IV_Requirement IVRequirement() const {return UNPREDICTABLE_RANDOM_IV;}
@ -193,13 +204,13 @@ public:
unsigned int MinLastBlockSize() const {return 0;} 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: public:
void ProcessBlocks(byte *outString, const byte *inString, unsigned int numberOfBlocks); 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: public:
void SetStolenIV(byte *iv) {m_stolenIV = iv;} void SetStolenIV(byte *iv) {m_stolenIV = iv;}
@ -216,7 +227,7 @@ protected:
byte *m_stolenIV; byte *m_stolenIV;
}; };
class CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase
{ {
public: public:
void ProcessBlocks(byte *outString, const byte *inString, unsigned int numberOfBlocks); void ProcessBlocks(byte *outString, const byte *inString, unsigned int numberOfBlocks);
@ -230,7 +241,7 @@ protected:
SecByteBlock m_temp; 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: public:
unsigned int MinLastBlockSize() const {return BlockSize()+1;} unsigned int MinLastBlockSize() const {return BlockSize()+1;}
@ -264,23 +275,31 @@ template <class BASE>
class CipherModeFinalTemplate_ExternalCipher : public BASE class CipherModeFinalTemplate_ExternalCipher : public BASE
{ {
public: public:
CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher) CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher);
{
CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize = 0);
};
template <class BASE> CipherModeFinalTemplate_ExternalCipher<BASE>::CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher)
{
ThrowIfResynchronizable(); ThrowIfResynchronizable();
m_cipher = &cipher; m_cipher = &cipher;
ResizeBuffers(); ResizeBuffers();
} }
CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize = 0) template <class BASE> CipherModeFinalTemplate_ExternalCipher<BASE>::CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize)
{ {
ThrowIfInvalidIV(iv); ThrowIfInvalidIV(iv);
m_cipher = &cipher; m_cipher = &cipher;
ResizeBuffers(); ResizeBuffers();
SetFeedbackSize(feedbackSize); SetFeedbackSize(feedbackSize);
if (IsResynchronizable()) if (IsResynchronizable())
Resynchronize(iv); Resynchronize(iv);
} }
};
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_CipherTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
//! CFB mode //! CFB mode
template <class CIPHER> template <class CIPHER>
@ -297,6 +316,8 @@ struct CFB_Mode_ExternalCipher : public CipherModeDocumentation
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption; typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> >;
//! OFB mode //! OFB mode
template <class CIPHER> template <class CIPHER>
struct OFB_Mode : public CipherModeDocumentation struct OFB_Mode : public CipherModeDocumentation
@ -312,6 +333,8 @@ struct OFB_Mode_ExternalCipher : public CipherModeDocumentation
typedef Encryption Decryption; typedef Encryption Decryption;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> >;
//! CTR mode //! CTR mode
template <class CIPHER> template <class CIPHER>
struct CTR_Mode : public CipherModeDocumentation struct CTR_Mode : public CipherModeDocumentation
@ -335,6 +358,8 @@ struct ECB_Mode : public CipherModeDocumentation
typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, ECB_OneWay> Decryption; typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, ECB_OneWay> Decryption;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ECB_OneWay>;
//! ECB mode, external cipher //! ECB mode, external cipher
struct ECB_Mode_ExternalCipher : public CipherModeDocumentation struct ECB_Mode_ExternalCipher : public CipherModeDocumentation
{ {
@ -350,6 +375,9 @@ struct CBC_Mode : public CipherModeDocumentation
typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_Decryption> Decryption; typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_Decryption> Decryption;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Decryption>;
//! CBC mode, external cipher //! CBC mode, external cipher
struct CBC_Mode_ExternalCipher : public CipherModeDocumentation struct CBC_Mode_ExternalCipher : public CipherModeDocumentation
{ {
@ -365,6 +393,9 @@ struct CBC_CTS_Mode : public CipherModeDocumentation
typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_CTS_Decryption> Decryption; typedef CipherModeFinalTemplate_CipherHolder<CPP_TYPENAME CIPHER::Decryption, CBC_CTS_Decryption> Decryption;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Decryption>;
//! CBC mode with ciphertext stealing, external cipher //! CBC mode with ciphertext stealing, external cipher
struct CBC_CTS_Mode_ExternalCipher : public CipherModeDocumentation struct CBC_CTS_Mode_ExternalCipher : public CipherModeDocumentation
{ {

View File

@ -1,16 +1,14 @@
// modexppc.cpp - written and placed in the public domain by Wei Dai // modexppc.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "modexppc.h" #include "modexppc.h"
#include "asn.h" #include "asn.h"
#include "algebra.cpp"
#include "eprecomp.cpp"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
template class DL_FixedBasePrecomputationImpl<Integer>;
/* /*
ModExpPrecomputation& ModExpPrecomputation::operator=(const ModExpPrecomputation &rhs) ModExpPrecomputation& ModExpPrecomputation::operator=(const ModExpPrecomputation &rhs)
{ {
@ -78,3 +76,5 @@ Integer ModExpPrecomputation::CascadeExponentiate(const Integer &exponent, const
*/ */
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -8,6 +8,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl<Integer>;
class ModExpPrecomputation : public DL_GroupPrecomputation<Integer> class ModExpPrecomputation : public DL_GroupPrecomputation<Integer>
{ {
public: public:

View File

@ -1,6 +1,9 @@
// mqueue.cpp - written and placed in the public domain by Wei Dai // mqueue.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "mqueue.h" #include "mqueue.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -180,3 +183,5 @@ bool EqualityComparisonFilter::HandleMismatchDetected(bool blocking)
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -8,7 +8,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! Message Queue //! Message Queue
class MessageQueue : public AutoSignaling<BufferedTransformation> class CRYPTOPP_DLL MessageQueue : public AutoSignaling<BufferedTransformation>
{ {
public: public:
MessageQueue(unsigned int nodeSize=256); MessageQueue(unsigned int nodeSize=256);
@ -62,7 +62,7 @@ private:
//! A filter that checks messages on two channels for equality //! A filter that checks messages on two channels for equality
class EqualityComparisonFilter : public Unflushable<Multichannel<Filter> > class CRYPTOPP_DLL EqualityComparisonFilter : public Unflushable<Multichannel<Filter> >
{ {
public: public:
struct MismatchDetected : public Exception {MismatchDetected() : Exception(DATA_INTEGRITY_CHECK_FAILED, "EqualityComparisonFilter: did not receive the same data on two channels") {}}; struct MismatchDetected : public Exception {MismatchDetected() : Exception(DATA_INTEGRITY_CHECK_FAILED, "EqualityComparisonFilter: did not receive the same data on two channels") {}};

View File

@ -1,6 +1,9 @@
// nbtheory.cpp - written and placed in the public domain by Wei Dai // nbtheory.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "nbtheory.h" #include "nbtheory.h"
#include "modarith.h" #include "modarith.h"
#include "algparam.h" #include "algparam.h"
@ -1125,3 +1128,5 @@ void PrimeAndGenerator::Generate(signed int delta, RandomNumberGenerator &rng, u
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -15,39 +15,39 @@ extern unsigned int primeTableSize;
extern word primeTable[]; extern word primeTable[];
// build up the table to maxPrimeTableSize // build up the table to maxPrimeTableSize
void BuildPrimeTable(); CRYPTOPP_DLL void BuildPrimeTable();
// ************ primality testing **************** // ************ primality testing ****************
// generate a provable prime // generate a provable prime
Integer MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits); CRYPTOPP_DLL Integer MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits);
Integer MihailescuProvablePrime(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 // returns true if p is divisible by some prime less than bound
// bound not be greater than the largest entry in the prime table // 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 // 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 // These is no reason to use these two, use the ones below instead
bool IsFermatProbablePrime(const Integer &n, const Integer &b); CRYPTOPP_DLL bool IsFermatProbablePrime(const Integer &n, const Integer &b);
bool IsLucasProbablePrime(const Integer &n); CRYPTOPP_DLL bool IsLucasProbablePrime(const Integer &n);
bool IsStrongProbablePrime(const Integer &n, const Integer &b); CRYPTOPP_DLL bool IsStrongProbablePrime(const Integer &n, const Integer &b);
bool IsStrongLucasProbablePrime(const Integer &n); CRYPTOPP_DLL bool IsStrongLucasProbablePrime(const Integer &n);
// Rabin-Miller primality test, i.e. repeating the strong probable prime test // Rabin-Miller primality test, i.e. repeating the strong probable prime test
// for several rounds with random bases // 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 // 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 // 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 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} // 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 // 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<AlgorithmParameters<AlgorithmParameters<NullNameValuePairs, Integer::RandomNumberType>, Integer>, Integer> CRYPTOPP_DLL AlgorithmParameters<AlgorithmParameters<AlgorithmParameters<NullNameValuePairs, Integer::RandomNumberType>, Integer>, Integer>
MakeParametersForTwoPrimesOfEqualSize(unsigned int productBitLength); MakeParametersForTwoPrimesOfEqualSize(unsigned int productBitLength);
// ********** other number theoretic functions ************ // ********** other number theoretic functions ************
@ -77,44 +77,44 @@ inline Integer EuclideanMultiplicativeInverse(const Integer &a, const Integer &b
{return a.InverseMod(b);} {return a.InverseMod(b);}
// use Chinese Remainder Theorem to calculate x given x mod p and x mod q // 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 // 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 // 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 // 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 // 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 // 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 // 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) inline Integer ModularExponentiation(const Integer &a, const Integer &e, const Integer &m)
{return a_exp_b_mod_c(a, e, m);} {return a_exp_b_mod_c(a, e, m);}
// returns x such that x*x%p == a, p prime // 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, // returns x such that a==ModularExponentiation(x, e, p*q), p q primes,
// and e relatively prime to (p-1)*(q-1) // 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)) // 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 // 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 // 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 // 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 // returns log base 2 of estimated number of operations to calculate discrete log or factor a number
unsigned int DiscreteLogWorkFactor(unsigned int bitlength); CRYPTOPP_DLL unsigned int DiscreteLogWorkFactor(unsigned int bitlength);
unsigned int FactoringWorkFactor(unsigned int bitlength); CRYPTOPP_DLL unsigned int FactoringWorkFactor(unsigned int bitlength);
// ******************************************************** // ********************************************************
//! generator of prime numbers of special forms //! generator of prime numbers of special forms
class PrimeAndGenerator class CRYPTOPP_DLL PrimeAndGenerator
{ {
public: public:
PrimeAndGenerator() {} PrimeAndGenerator() {}

3
oaep.h
View File

@ -2,6 +2,7 @@
#define CRYPTOPP_OAEP_H #define CRYPTOPP_OAEP_H
#include "pubkey.h" #include "pubkey.h"
#include "sha.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -20,6 +21,8 @@ public:
DecodingResult Unpad(const byte *padded, unsigned int paddedLength, byte *raw) const; DecodingResult Unpad(const byte *padded, unsigned int paddedLength, byte *raw) const;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS OAEP<SHA>;
NAMESPACE_END NAMESPACE_END
#endif #endif

View File

@ -3,6 +3,9 @@
// Thanks to Leonard Janke for the suggestion for AutoSeededRandomPool. // Thanks to Leonard Janke for the suggestion for AutoSeededRandomPool.
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "osrng.h" #include "osrng.h"
#ifdef OS_RNG_AVAILABLE #ifdef OS_RNG_AVAILABLE
@ -170,3 +173,5 @@ void AutoSeededRandomPool::Reseed(bool blocking, unsigned int seedSize)
NAMESPACE_END NAMESPACE_END
#endif #endif
#endif

17
osrng.h
View File

@ -7,11 +7,12 @@
#include "randpool.h" #include "randpool.h"
#include "rng.h" #include "rng.h"
#include "des.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! Exception class for Operating-System Random Number Generator. //! Exception class for Operating-System Random Number Generator.
class OS_RNG_Err : public Exception class CRYPTOPP_DLL OS_RNG_Err : public Exception
{ {
public: public:
OS_RNG_Err(const std::string &operation); OS_RNG_Err(const std::string &operation);
@ -20,7 +21,7 @@ public:
#ifdef NONBLOCKING_RNG_AVAILABLE #ifdef NONBLOCKING_RNG_AVAILABLE
#ifdef CRYPTOPP_WIN32_AVAILABLE #ifdef CRYPTOPP_WIN32_AVAILABLE
class MicrosoftCryptoProvider class CRYPTOPP_DLL MicrosoftCryptoProvider
{ {
public: public:
MicrosoftCryptoProvider(); MicrosoftCryptoProvider();
@ -37,7 +38,7 @@ private:
#endif #endif
//! encapsulate CryptoAPI's CryptGenRandom or /dev/urandom //! encapsulate CryptoAPI's CryptGenRandom or /dev/urandom
class NonblockingRng : public RandomNumberGenerator class CRYPTOPP_DLL NonblockingRng : public RandomNumberGenerator
{ {
public: public:
NonblockingRng(); NonblockingRng();
@ -60,7 +61,7 @@ protected:
#ifdef BLOCKING_RNG_AVAILABLE #ifdef BLOCKING_RNG_AVAILABLE
//! encapsulate /dev/random //! encapsulate /dev/random
class BlockingRng : public RandomNumberGenerator class CRYPTOPP_DLL BlockingRng : public RandomNumberGenerator
{ {
public: public:
BlockingRng(); BlockingRng();
@ -74,11 +75,11 @@ protected:
#endif #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 //! Automaticly Seeded Randomness Pool
/*! This class seeds itself using an operating system provided RNG. */ /*! This class seeds itself using an operating system provided RNG. */
class AutoSeededRandomPool : public RandomPool class CRYPTOPP_DLL AutoSeededRandomPool : public RandomPool
{ {
public: public:
//! blocking will be ignored if the prefered RNG isn't available //! 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 //! RNG from ANSI X9.17 Appendix C, seeded using an OS provided RNG
template <class BLOCK_CIPHER> template <class BLOCK_CIPHER>
class AutoSeededX917RNG : public RandomNumberGenerator class AutoSeededX917RNG : public RandomNumberGenerator, public NotCopyable
{ {
public: public:
//! blocking will be ignored if the prefered RNG isn't available //! blocking will be ignored if the prefered RNG isn't available
@ -108,6 +109,8 @@ private:
unsigned int m_counter; unsigned int m_counter;
}; };
CRYPTOPP_DLL_TEMPLATE_CLASS AutoSeededX917RNG<DES_EDE3>;
template <class BLOCK_CIPHER> template <class BLOCK_CIPHER>
void AutoSeededX917RNG<BLOCK_CIPHER>::Reseed(const byte *key, unsigned int keylength, const byte *seed, unsigned long timeVector) void AutoSeededX917RNG<BLOCK_CIPHER>::Reseed(const byte *key, unsigned int keylength, const byte *seed, unsigned long timeVector)
{ {

View File

@ -101,7 +101,7 @@ void PanamaHash<B>::TruncatedFinal(byte *hash, unsigned int size)
PadLastBlock(BLOCKSIZE, 0x01); PadLastBlock(BLOCKSIZE, 0x01);
vTransform(m_data); HashEndianCorrectedBlock(m_data);
Iterate(32); // pull Iterate(32); // pull

View File

@ -30,13 +30,13 @@ class PanamaHash : protected Panama<B>, public IteratedHash<word32, NativeByteOr
{ {
public: public:
enum {DIGESTSIZE = 32}; enum {DIGESTSIZE = 32};
PanamaHash() : IteratedHash<word32, NativeByteOrder, 32>(0) {Panama<B>::Reset();} PanamaHash() {Panama<B>::Reset();}
unsigned int DigestSize() const {return DIGESTSIZE;} unsigned int DigestSize() const {return DIGESTSIZE;}
void TruncatedFinal(byte *hash, unsigned int size); void TruncatedFinal(byte *hash, unsigned int size);
protected: protected:
void Init() {Panama<B>::Reset();} void Init() {Panama<B>::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); unsigned int HashMultipleBlocks(const word32 *input, unsigned int length);
}; };
@ -65,7 +65,7 @@ protected:
/// Panama MAC /// Panama MAC
template <class B = LittleEndian> template <class B = LittleEndian>
class PanamaMAC : public MessageAuthenticationCodeTemplate<PanamaMAC_Base<B> > class PanamaMAC : public MessageAuthenticationCodeImpl<PanamaMAC_Base<B> >
{ {
public: public:
PanamaMAC() {} PanamaMAC() {}
@ -96,7 +96,7 @@ protected:
template <class B = LittleEndian> template <class B = LittleEndian>
struct PanamaCipher : public PanamaCipherInfo<B>, public SymmetricCipherDocumentation struct PanamaCipher : public PanamaCipherInfo<B>, public SymmetricCipherDocumentation
{ {
typedef SymmetricCipherFinalTemplate<ConcretePolicyHolder<PanamaCipherPolicy<B>, AdditiveCipherTemplate<> > > Encryption; typedef SymmetricCipherFinal<ConcretePolicyHolder<PanamaCipherPolicy<B>, AdditiveCipherTemplate<> > > Encryption;
typedef Encryption Decryption; typedef Encryption Decryption;
}; };

View File

@ -1,14 +1,12 @@
// pkcspad.cpp - written and placed in the public domain by Wei Dai // pkcspad.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#include "pkcspad.h" #include "pkcspad.h"
#include <assert.h> #include <assert.h>
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
template<> const byte PKCS_DigestDecoration<SHA>::decoration[] = {0x30,0x21,0x30,0x09,0x06,0x05,0x2B,0x0E,0x03,0x02,0x1A,0x05,0x00,0x04,0x14};
template<> const unsigned int PKCS_DigestDecoration<SHA>::length = sizeof(PKCS_DigestDecoration<SHA>::decoration);
template<> const byte PKCS_DigestDecoration<MD2>::decoration[] = {0x30,0x20,0x30,0x0c,0x06,0x08,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x02,0x02,0x05,0x00,0x04,0x10}; template<> const byte PKCS_DigestDecoration<MD2>::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<MD2>::length = sizeof(PKCS_DigestDecoration<MD2>::decoration); template<> const unsigned int PKCS_DigestDecoration<MD2>::length = sizeof(PKCS_DigestDecoration<MD2>::decoration);
@ -91,6 +89,8 @@ DecodingResult PKCS_EncryptionPaddingScheme::Unpad(const byte *pkcsBlock, unsign
// ******************************************************** // ********************************************************
#ifndef CRYPTOPP_IMPORTS
void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(RandomNumberGenerator &rng, void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(RandomNumberGenerator &rng,
const byte *recoverableMessage, unsigned int recoverableMessageLength, const byte *recoverableMessage, unsigned int recoverableMessageLength,
HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty, HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
@ -123,4 +123,6 @@ void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(Rando
hash.Final(pDigest); hash.Final(pDigest);
} }
#endif
NAMESPACE_END NAMESPACE_END

View File

@ -4,6 +4,10 @@
#include "cryptlib.h" #include "cryptlib.h"
#include "pubkey.h" #include "pubkey.h"
#ifdef CRYPTOPP_IS_DLL
#include "sha.h"
#endif
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! <a href="http://www.weidai.com/scan-mirror/ca.html#cem_PKCS1-1.5">EME-PKCS1-v1_5</a> //! <a href="http://www.weidai.com/scan-mirror/ca.html#cem_PKCS1-1.5">EME-PKCS1-v1_5</a>
@ -17,14 +21,15 @@ public:
DecodingResult Unpad(const byte *padded, unsigned int paddedLength, byte *raw) const; DecodingResult Unpad(const byte *padded, unsigned int paddedLength, byte *raw) const;
}; };
template <class H> struct PKCS_DigestDecoration template <class H> class PKCS_DigestDecoration
{ {
public:
static const byte decoration[]; static const byte decoration[];
static const unsigned int length; static const unsigned int length;
}; };
//! <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PKCS1-1.5">EMSA-PKCS1-v1_5</a> //! <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PKCS1-1.5">EMSA-PKCS1-v1_5</a>
class PKCS1v15_SignatureMessageEncodingMethod : public PK_DeterministicSignatureMessageEncodingMethod class CRYPTOPP_DLL PKCS1v15_SignatureMessageEncodingMethod : public PK_DeterministicSignatureMessageEncodingMethod
{ {
public: public:
static const char * StaticAlgorithmName() {return "EMSA-PKCS1-v1_5";} 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. */ /*! The following hash functions are supported for signature: SHA, MD2, MD5, RIPEMD160, SHA256, SHA384, SHA512. */
struct PKCS1v15 : public SignatureStandard, public EncryptionStandard struct PKCS1v15 : public SignatureStandard, public EncryptionStandard
{ {
@ -54,6 +59,10 @@ struct PKCS1v15 : public SignatureStandard, public EncryptionStandard
typedef PKCS1v15_SignatureMessageEncodingMethod SignatureMessageEncodingMethod; typedef PKCS1v15_SignatureMessageEncodingMethod SignatureMessageEncodingMethod;
}; };
#ifdef CRYPTOPP_IS_DLL
CRYPTOPP_DLL_TEMPLATE_CLASS PKCS_DigestDecoration<SHA>;
#endif
// PKCS_DecoratedHashModule can be instantiated with the following // PKCS_DecoratedHashModule can be instantiated with the following
// classes as specified in PKCS#1 v2.0 and P1363a // classes as specified in PKCS#1 v2.0 and P1363a
class SHA; class SHA;

View File

@ -1,6 +1,9 @@
// pubkey.cpp - written and placed in the public domain by Wei Dai // pubkey.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "pubkey.h" #include "pubkey.h"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
@ -120,3 +123,5 @@ void TF_EncryptorBase::Encrypt(RandomNumberGenerator &rng, const byte *plainText
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -44,13 +44,8 @@
NAMESPACE_BEGIN(CryptoPP) 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: public:
virtual ~TrapdoorFunctionBounds() {} virtual ~TrapdoorFunctionBounds() {}
@ -62,7 +57,7 @@ public:
}; };
//! . //! .
class CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunction : public TrapdoorFunctionBounds class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomizedTrapdoorFunction : public TrapdoorFunctionBounds
{ {
public: public:
virtual Integer ApplyRandomizedFunction(RandomNumberGenerator &rng, const Integer &x) const =0; 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: public:
Integer ApplyRandomizedFunction(RandomNumberGenerator &rng, const Integer &x) const 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: public:
virtual ~RandomizedTrapdoorFunctionInverse() {} virtual ~RandomizedTrapdoorFunctionInverse() {}
@ -91,7 +86,7 @@ public:
}; };
//! . //! .
class CRYPTOPP_NO_VTABLE TrapdoorFunctionInverse : public RandomizedTrapdoorFunctionInverse class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TrapdoorFunctionInverse : public RandomizedTrapdoorFunctionInverse
{ {
public: public:
virtual ~TrapdoorFunctionInverse() {} virtual ~TrapdoorFunctionInverse() {}
@ -151,14 +146,14 @@ protected:
}; };
//! . //! .
class CRYPTOPP_NO_VTABLE TF_DecryptorBase : public TF_CryptoSystemBase<PK_FixedLengthDecryptor, TF_Base<TrapdoorFunctionInverse, PK_EncryptionMessageEncodingMethod> > class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_DecryptorBase : public TF_CryptoSystemBase<PK_FixedLengthDecryptor, TF_Base<TrapdoorFunctionInverse, PK_EncryptionMessageEncodingMethod> >
{ {
public: public:
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *cipherText, byte *plainText) const; DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *cipherText, byte *plainText) const;
}; };
//! . //! .
class CRYPTOPP_NO_VTABLE TF_EncryptorBase : public TF_CryptoSystemBase<PK_FixedLengthEncryptor, TF_Base<RandomizedTrapdoorFunction, PK_EncryptionMessageEncodingMethod> > class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_EncryptorBase : public TF_CryptoSystemBase<PK_FixedLengthEncryptor, TF_Base<RandomizedTrapdoorFunction, PK_EncryptionMessageEncodingMethod> >
{ {
public: public:
void Encrypt(RandomNumberGenerator &rng, const byte *plainText, unsigned int plainTextLength, byte *cipherText) const; 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: public:
bool VerifyMessageRepresentative( bool VerifyMessageRepresentative(
@ -240,7 +235,7 @@ public:
byte *representative, unsigned int representativeBitLength) const; 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: public:
bool VerifyMessageRepresentative( bool VerifyMessageRepresentative(
@ -248,7 +243,7 @@ public:
byte *representative, unsigned int representativeBitLength) const; byte *representative, unsigned int representativeBitLength) const;
}; };
class DL_SignatureMessageEncodingMethod_DSA : public PK_DeterministicSignatureMessageEncodingMethod class CRYPTOPP_DLL DL_SignatureMessageEncodingMethod_DSA : public PK_DeterministicSignatureMessageEncodingMethod
{ {
public: public:
void ComputeMessageRepresentative(RandomNumberGenerator &rng, void ComputeMessageRepresentative(RandomNumberGenerator &rng,
@ -257,7 +252,7 @@ public:
byte *representative, unsigned int representativeBitLength) const; byte *representative, unsigned int representativeBitLength) const;
}; };
class DL_SignatureMessageEncodingMethod_NR : public PK_DeterministicSignatureMessageEncodingMethod class CRYPTOPP_DLL DL_SignatureMessageEncodingMethod_NR : public PK_DeterministicSignatureMessageEncodingMethod
{ {
public: public:
void ComputeMessageRepresentative(RandomNumberGenerator &rng, void ComputeMessageRepresentative(RandomNumberGenerator &rng,
@ -266,7 +261,7 @@ public:
byte *representative, unsigned int representativeBitLength) const; 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: public:
PK_MessageAccumulatorBase() : m_empty(true) {} PK_MessageAccumulatorBase() : m_empty(true) {}
@ -318,7 +313,7 @@ protected:
}; };
//! . //! .
class CRYPTOPP_NO_VTABLE TF_SignerBase : public TF_SignatureSchemeBase<PK_Signer, TF_Base<RandomizedTrapdoorFunctionInverse, PK_SignatureMessageEncodingMethod> > class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_SignerBase : public TF_SignatureSchemeBase<PK_Signer, TF_Base<RandomizedTrapdoorFunctionInverse, PK_SignatureMessageEncodingMethod> >
{ {
public: public:
void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, unsigned int recoverableMessageLength) const; 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<PK_Verifier, TF_Base<TrapdoorFunction, PK_SignatureMessageEncodingMethod> > class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TF_VerifierBase : public TF_SignatureSchemeBase<PK_Verifier, TF_Base<TrapdoorFunction, PK_SignatureMessageEncodingMethod> >
{ {
public: public:
void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, unsigned int signatureLength) const; 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; 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 class P1363_MGF1 : public MaskGeneratingFunction
@ -625,7 +620,7 @@ private:
}; };
//! . //! .
template <class GROUP_PRECOMP, class BASE_PRECOMP = DL_FixedBasePrecomputationImpl<typename GROUP_PRECOMP::Element>, class BASE = DL_GroupParameters<typename GROUP_PRECOMP::Element> > template <class GROUP_PRECOMP, class BASE_PRECOMP = DL_FixedBasePrecomputationImpl<CPP_TYPENAME GROUP_PRECOMP::Element>, class BASE = DL_GroupParameters<CPP_TYPENAME GROUP_PRECOMP::Element> >
class DL_GroupParametersImpl : public BASE class DL_GroupParametersImpl : public BASE
{ {
public: public:
@ -637,6 +632,9 @@ public:
const DL_FixedBasePrecomputation<Element> & GetBasePrecomputation() const {return m_gpc;} const DL_FixedBasePrecomputation<Element> & GetBasePrecomputation() const {return m_gpc;}
DL_FixedBasePrecomputation<Element> & AccessBasePrecomputation() {return m_gpc;} DL_FixedBasePrecomputation<Element> & AccessBasePrecomputation() {return m_gpc;}
bool operator==(const DL_GroupParametersImpl<GROUP_PRECOMP, BASE_PRECOMP, BASE> &rhs) const
{return m_groupPrecomputation.GetCurve() == rhs.m_groupPrecomputation.GetCurve() && m_gpc.GetBase(m_groupPrecomputation) == rhs.m_gpc.GetBase(rhs.m_groupPrecomputation);}
protected: protected:
GROUP_PRECOMP m_groupPrecomputation; GROUP_PRECOMP m_groupPrecomputation;
BASE_PRECOMP m_gpc; BASE_PRECOMP m_gpc;
@ -916,7 +914,6 @@ template <class T>
class CRYPTOPP_NO_VTABLE DL_ElgamalLikeSignatureAlgorithm class CRYPTOPP_NO_VTABLE DL_ElgamalLikeSignatureAlgorithm
{ {
public: public:
// virtual Integer EncodeDigest(unsigned int modulusBits, const byte *digest, unsigned int digestLength) const =0;
virtual void Sign(const DL_GroupParameters<T> &params, const Integer &privateKey, const Integer &k, const Integer &e, Integer &r, Integer &s) const =0; virtual void Sign(const DL_GroupParameters<T> &params, const Integer &privateKey, const Integer &k, const Integer &e, Integer &r, Integer &s) const =0;
virtual bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const =0; virtual bool Verify(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &e, const Integer &r, const Integer &s) const =0;
virtual Integer RecoverPresignature(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &r, const Integer &s) const virtual Integer RecoverPresignature(const DL_GroupParameters<T> &params, const DL_PublicKey<T> &publicKey, const Integer &r, const Integer &s) const

View File

@ -1,6 +1,9 @@
// queue.cpp - written and placed in the public domain by Wei Dai // queue.cpp - written and placed in the public domain by Wei Dai
#include "pch.h" #include "pch.h"
#ifndef CRYPTOPP_IMPORTS
#include "queue.h" #include "queue.h"
#include "filters.h" #include "filters.h"
@ -548,3 +551,5 @@ unsigned int ByteQueue::Walker::CopyRangeTo2(BufferedTransformation &target, uns
} }
NAMESPACE_END NAMESPACE_END
#endif

View File

@ -13,7 +13,7 @@ NAMESPACE_BEGIN(CryptoPP)
class ByteQueueNode; class ByteQueueNode;
//! Byte Queue //! Byte Queue
class ByteQueue : public Bufferless<BufferedTransformation> class CRYPTOPP_DLL ByteQueue : public Bufferless<BufferedTransformation>
{ {
public: public:
ByteQueue(unsigned int m_nodeSize=0); ByteQueue(unsigned int m_nodeSize=0);
@ -108,7 +108,7 @@ private:
}; };
//! use this to make sure LazyPut is finalized in event of exception //! use this to make sure LazyPut is finalized in event of exception
class LazyPutter class CRYPTOPP_DLL LazyPutter
{ {
public: public:
LazyPutter(ByteQueue &bq, const byte *inString, unsigned int size) LazyPutter(ByteQueue &bq, const byte *inString, unsigned int size)

View File

@ -7,8 +7,6 @@
#include "sha.h" #include "sha.h"
#include "modarith.h" #include "modarith.h"
#include "oaep.cpp"
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
void RabinFunction::BERDecode(BufferedTransformation &bt) void RabinFunction::BERDecode(BufferedTransformation &bt)

Some files were not shown because too many files have changed in this diff Show More