Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | File List | Class Members | File Members

cryptlib.h

Go to the documentation of this file.
00001 // cryptlib.h - written and placed in the public domain by Wei Dai 00002 /*! \file 00003 This file contains the declarations for the abstract base 00004 classes that provide a uniform interface to this library. 00005 */ 00006 00007 /*! \mainpage <a href="http://www.cryptopp.com">Crypto++</a><sup><small>TM</small></sup> Library 5.2.1 Reference Manual 00008 <dl> 00009 <dt>Abstract Base Classes<dd> 00010 cryptlib.h 00011 <dt>Symmetric Ciphers<dd> 00012 SymmetricCipherDocumentation 00013 <dt>Hash Functions<dd> 00014 HAVAL, MD2, MD4, MD5, PanamaHash, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, SHA, SHA256, SHA384, SHA512, Tiger, Whirlpool 00015 <dt>Non-Cryptographic Checksums<dd> 00016 CRC32, Adler32 00017 <dt>Message Authentication Codes<dd> 00018 #MD5MAC, XMACC, HMAC, CBC_MAC, DMAC, PanamaMAC, TTMAC 00019 <dt>Random Number Generators<dd> 00020 NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG 00021 <dt>Password-based Cryptography<dd> 00022 PasswordBasedKeyDerivationFunction 00023 <dt>Public Key Cryptosystems<dd> 00024 DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES 00025 <dt>Public Key Signature Schemes<dd> 00026 DSA, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RabinSS, RWSS, ESIGN 00027 <dt>Key Agreement<dd> 00028 #DH, DH2, #MQV, ECDH, ECMQV, XTR_DH 00029 <dt>Algebraic Structures<dd> 00030 Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver, 00031 ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, 00032 GF2NP, GF256, GF2_32, EC2N, ECP 00033 <dt>Secret Sharing and Information Dispersal<dd> 00034 SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery 00035 <dt>Compression<dd> 00036 Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor 00037 <dt>Input Source Classes<dd> 00038 StringSource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource 00039 <dt>Output Sink Classes<dd> 00040 StringSinkTemplate, ArraySink, FileSink, SocketSink, WindowsPipeSink 00041 <dt>Filter Wrappers<dd> 00042 StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter 00043 <dt>Binary to Text Encoders and Decoders<dd> 00044 HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base32Encoder, Base32Decoder 00045 <dt>Wrappers for OS features<dd> 00046 Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer 00047 <dt>FIPS 140 related<dd> 00048 fips140.h 00049 </dl> 00050 00051 In the FIPS 140-2 validated DLL version of Crypto++, only the following implementation class are available. 00052 <dl> 00053 <dt>Block Ciphers<dd> 00054 AES, DES_EDE2, DES_EDE3, SKIPJACK 00055 <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd> 00056 ECB_Mode<BC>, CTR_Mode<BC>, CBC_Mode<BC>, CFB_Mode<BC>, OFB_Mode<BC> 00057 <dt>Hash Functions<dd> 00058 SHA 00059 <dt>Public Key Signature Schemes<dd> 00060 RSASS<PKCS1v15, SHA>, DSA, ECDSA<ECP, SHA>, ECDSA<EC2N, SHA> 00061 <dt>Message Authentication Codes<dd> 00062 HMAC<SHA>, CBC_MAC<DES_EDE2>, CBC_MAC<DES_EDE3> 00063 <dt>Random Number Generators<dd> 00064 AutoSeededX917RNG<DES_EDE3> 00065 <dt>Key Agreement<dd> 00066 #DH 00067 <dt>Public Key Cryptosystems<dd> 00068 RSAES<OAEP<SHA> > 00069 </dl> 00070 00071 <p>This reference manual is a work in progress. Some classes are still lacking detailed descriptions. 00072 <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual. 00073 <p>Thanks to Ryan Phillips for providing the Doxygen configuration file 00074 and getting me started with this manual. 00075 */ 00076 00077 #ifndef CRYPTOPP_CRYPTLIB_H 00078 #define CRYPTOPP_CRYPTLIB_H 00079 00080 #include "config.h" 00081 #include "stdcpp.h" 00082 00083 NAMESPACE_BEGIN(CryptoPP) 00084 00085 // forward declarations 00086 class Integer; 00087 00088 //! used to specify a direction for a cipher to operate in (encrypt or decrypt) 00089 enum CipherDir {ENCRYPTION, DECRYPTION}; 00090 00091 //! used to represent infinite time 00092 const unsigned long INFINITE_TIME = ULONG_MAX; 00093 00094 // VC60 workaround: using enums as template parameters causes problems 00095 template <typename ENUM_TYPE, int VALUE> 00096 struct EnumToType 00097 { 00098 static ENUM_TYPE ToEnum() {return (ENUM_TYPE)VALUE;} 00099 }; 00100 00101 enum ByteOrder {LITTLE_ENDIAN_ORDER = 0, BIG_ENDIAN_ORDER = 1}; 00102 typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian; 00103 typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian; 00104 00105 //! base class for all exceptions thrown by Crypto++ 00106 class CRYPTOPP_DLL Exception : public std::exception 00107 { 00108 public: 00109 //! error types 00110 enum ErrorType { 00111 //! a method is not implemented 00112 NOT_IMPLEMENTED, 00113 //! invalid function argument 00114 INVALID_ARGUMENT, 00115 //! BufferedTransformation received a Flush(true) signal but can't flush buffers 00116 CANNOT_FLUSH, 00117 //! data integerity check (such as CRC or MAC) failed 00118 DATA_INTEGRITY_CHECK_FAILED, 00119 //! received input data that doesn't conform to expected format 00120 INVALID_DATA_FORMAT, 00121 //! error reading from input device or writing to output device 00122 IO_ERROR, 00123 //! some error not belong to any of the above categories 00124 OTHER_ERROR 00125 }; 00126 00127 explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {} 00128 virtual ~Exception() throw() {} 00129 const char *what() const throw() {return (m_what.c_str());} 00130 const std::string &GetWhat() const {return m_what;} 00131 void SetWhat(const std::string &s) {m_what = s;} 00132 ErrorType GetErrorType() const {return m_errorType;} 00133 void SetErrorType(ErrorType errorType) {m_errorType = errorType;} 00134 00135 private: 00136 ErrorType m_errorType; 00137 std::string m_what; 00138 }; 00139 00140 //! exception thrown when an invalid argument is detected 00141 class CRYPTOPP_DLL InvalidArgument : public Exception 00142 { 00143 public: 00144 explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {} 00145 }; 00146 00147 //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext 00148 class CRYPTOPP_DLL InvalidDataFormat : public Exception 00149 { 00150 public: 00151 explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {} 00152 }; 00153 00154 //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext 00155 class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat 00156 { 00157 public: 00158 explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {} 00159 }; 00160 00161 //! exception thrown by a class if a non-implemented method is called 00162 class CRYPTOPP_DLL NotImplemented : public Exception 00163 { 00164 public: 00165 explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {} 00166 }; 00167 00168 //! exception thrown by a class when Flush(true) is called but it can't completely flush its buffers 00169 class CRYPTOPP_DLL CannotFlush : public Exception 00170 { 00171 public: 00172 explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {} 00173 }; 00174 00175 //! error reported by the operating system 00176 class CRYPTOPP_DLL OS_Error : public Exception 00177 { 00178 public: 00179 OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode) 00180 : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {} 00181 ~OS_Error() throw() {} 00182 00183 // the operating system API that reported the error 00184 const std::string & GetOperation() const {return m_operation;} 00185 // the error code return by the operating system 00186 int GetErrorCode() const {return m_errorCode;} 00187 00188 protected: 00189 std::string m_operation; 00190 int m_errorCode; 00191 }; 00192 00193 //! used to return decoding results 00194 struct CRYPTOPP_DLL DecodingResult 00195 { 00196 explicit DecodingResult() : isValidCoding(false), messageLength(0) {} 00197 explicit DecodingResult(unsigned int len) : isValidCoding(true), messageLength(len) {} 00198 00199 bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;} 00200 bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);} 00201 00202 bool isValidCoding; 00203 unsigned int messageLength; 00204 00205 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 00206 operator unsigned int() const {return isValidCoding ? messageLength : 0;} 00207 #endif 00208 }; 00209 00210 //! interface for retrieving values given their names 00211 /*! \note This class is used to safely pass a variable number of arbitrarily typed arguments to functions 00212 and to read values from keys and crypto parameters. 00213 \note To obtain an object that implements NameValuePairs for the purpose of parameter 00214 passing, use the MakeParameters() function. 00215 \note To get a value from NameValuePairs, you need to know the name and the type of the value. 00216 Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports. 00217 Then look at the Name namespace documentation to see what the type of each value is, or 00218 alternatively, call GetIntValue() with the value name, and if the type is not int, a 00219 ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object. 00220 */ 00221 class CRYPTOPP_NO_VTABLE NameValuePairs 00222 { 00223 public: 00224 virtual ~NameValuePairs() {} 00225 00226 //! exception thrown when trying to retrieve a value using a different type than expected 00227 class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument 00228 { 00229 public: 00230 ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving) 00231 : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'") 00232 , m_stored(stored), m_retrieving(retrieving) {} 00233 00234 const std::type_info & GetStoredTypeInfo() const {return m_stored;} 00235 const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;} 00236 00237 private: 00238 const std::type_info &m_stored; 00239 const std::type_info &m_retrieving; 00240 }; 00241 00242 //! get a copy of this object or a subobject of it 00243 template <class T> 00244 bool GetThisObject(T &object) const 00245 { 00246 return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object); 00247 } 00248 00249 //! get a pointer to this object, as a pointer to T 00250 template <class T> 00251 bool GetThisPointer(T *&p) const 00252 { 00253 return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), p); 00254 } 00255 00256 //! get a named value, returns true if the name exists 00257 template <class T> 00258 bool GetValue(const char *name, T &value) const 00259 { 00260 return GetVoidValue(name, typeid(T), &value); 00261 } 00262 00263 //! get a named value, returns the default if the name doesn't exist 00264 template <class T> 00265 T GetValueWithDefault(const char *name, T defaultValue) const 00266 { 00267 GetValue(name, defaultValue); 00268 return defaultValue; 00269 } 00270 00271 //! get a list of value names that can be retrieved 00272 CRYPTOPP_DLL std::string GetValueNames() const 00273 {std::string result; GetValue("ValueNames", result); return result;} 00274 00275 //! get a named value with type int 00276 /*! used to ensure we don't accidentally try to get an unsigned int 00277 or some other type when we mean int (which is the most common case) */ 00278 CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const 00279 {return GetValue(name, value);} 00280 00281 //! get a named value with type int, with default 00282 CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const 00283 {return GetValueWithDefault(name, defaultValue);} 00284 00285 //! used by derived classes to check for type mismatch 00286 CRYPTOPP_DLL static void ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving) 00287 {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);} 00288 00289 template <class T> 00290 void GetRequiredParameter(const char *className, const char *name, T &value) const 00291 { 00292 if (!GetValue(name, value)) 00293 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); 00294 } 00295 00296 CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const 00297 { 00298 if (!GetIntValue(name, value)) 00299 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); 00300 } 00301 00302 //! to be implemented by derived classes, users should use one of the above functions instead 00303 CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0; 00304 }; 00305 00306 //! namespace containing value name definitions 00307 /*! value names, types and semantics: 00308 00309 ThisObject:ClassName (ClassName, copy of this object or a subobject) 00310 ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject) 00311 */ 00312 DOCUMENTED_NAMESPACE_BEGIN(Name) 00313 // more names defined in argnames.h 00314 DOCUMENTED_NAMESPACE_END 00315 00316 //! empty set of name-value pairs 00317 class CRYPTOPP_DLL NullNameValuePairs : public NameValuePairs 00318 { 00319 public: 00320 bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const {return false;} 00321 }; 00322 00323 //! _ 00324 extern CRYPTOPP_DLL const NullNameValuePairs g_nullNameValuePairs; 00325 00326 // ******************************************************** 00327 00328 //! interface for cloning objects, this is not implemented by most classes yet 00329 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable 00330 { 00331 public: 00332 virtual ~Clonable() {} 00333 //! this is not implemented by most classes yet 00334 virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0 00335 }; 00336 00337 //! interface for all crypto algorithms 00338 00339 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable 00340 { 00341 public: 00342 /*! When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true, 00343 this constructor throws SelfTestFailure if the self test hasn't been run or fails. */ 00344 Algorithm(bool checkSelfTestStatus = true); 00345 //! returns name of this algorithm, not universally implemented yet 00346 virtual std::string AlgorithmName() const {return "unknown";} 00347 }; 00348 00349 //! keying interface for crypto algorithms that take byte strings as keys 00350 00351 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface 00352 { 00353 public: 00354 //! returns smallest valid key length in bytes */ 00355 virtual unsigned int MinKeyLength() const =0; 00356 //! returns largest valid key length in bytes */ 00357 virtual unsigned int MaxKeyLength() const =0; 00358 //! returns default (recommended) key length in bytes */ 00359 virtual unsigned int DefaultKeyLength() const =0; 00360 00361 //! returns the smallest valid key length in bytes that is >= min(n, GetMaxKeyLength()) 00362 virtual unsigned int GetValidKeyLength(unsigned int n) const =0; 00363 00364 //! returns whether n is a valid key length 00365 virtual bool IsValidKeyLength(unsigned int n) const 00366 {return n == GetValidKeyLength(n);} 00367 00368 //! set or reset the key of this object 00369 /*! \param params is used to specify Rounds, BlockSize, etc */ 00370 virtual void SetKey(const byte *key, unsigned int length, const NameValuePairs &params = g_nullNameValuePairs) =0; 00371 00372 //! calls SetKey() with an NameValuePairs object that just specifies "Rounds" 00373 void SetKeyWithRounds(const byte *key, unsigned int length, int rounds); 00374 00375 //! calls SetKey() with an NameValuePairs object that just specifies "IV" 00376 void SetKeyWithIV(const byte *key, unsigned int length, const byte *iv); 00377 00378 enum IV_Requirement {STRUCTURED_IV = 0, RANDOM_IV, UNPREDICTABLE_RANDOM_IV, INTERNALLY_GENERATED_IV, NOT_RESYNCHRONIZABLE}; 00379 //! returns the minimal requirement for secure IVs 00380 virtual IV_Requirement IVRequirement() const =0; 00381 00382 //! returns whether this object can be resynchronized (i.e. supports initialization vectors) 00383 /*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */ 00384 bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;} 00385 //! returns whether this object can use random IVs (in addition to ones returned by GetNextIV) 00386 bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;} 00387 //! returns whether this object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV) 00388 bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;} 00389 //! returns whether this object can use structured IVs, for example a counter (in addition to ones returned by GetNextIV) 00390 bool CanUseStructuredIVs() const {return IVRequirement() <= STRUCTURED_IV;} 00391 00392 //! returns size of IVs used by this object 00393 virtual unsigned int IVSize() const {throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");} 00394 //! resynchronize with an IV 00395 virtual void Resynchronize(const byte *IV) {throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");} 00396 //! get a secure IV for the next message 00397 /*! This method should be called after you finish encrypting one message and are ready to start the next one. 00398 After calling it, you must call SetKey() or Resynchronize() before using this object again. 00399 This method is not implemented on decryption objects. */ 00400 virtual void GetNextIV(byte *IV) {throw NotImplemented("SimpleKeyingInterface: this object doesn't support GetNextIV()");} 00401 00402 protected: 00403 void ThrowIfInvalidKeyLength(const Algorithm &algorithm, unsigned int length); 00404 void ThrowIfResynchronizable(); // to be called when no IV is passed 00405 void ThrowIfInvalidIV(const byte *iv); // check for NULL IV if it can't be used 00406 const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params); 00407 00408 inline void AssertValidKeyLength(unsigned int length) const 00409 { 00410 assert(IsValidKeyLength(length)); 00411 } 00412 }; 00413 00414 //! interface for the data processing part of block ciphers 00415 00416 /*! Classes derived from BlockTransformation are block ciphers 00417 in ECB mode (for example the DES::Encryption class), which are stateless, 00418 and they can make assumptions about the memory alignment of their inputs and outputs. 00419 These classes should not be used directly, but only in combination with 00420 a mode class (see CipherModeDocumentation in modes.h). 00421 */ 00422 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm 00423 { 00424 public: 00425 //! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock 00426 virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0; 00427 00428 //! encrypt or decrypt one block 00429 /*! \pre size of inBlock and outBlock == BlockSize() */ 00430 void ProcessBlock(const byte *inBlock, byte *outBlock) const 00431 {ProcessAndXorBlock(inBlock, NULL, outBlock);} 00432 00433 //! encrypt or decrypt one block in place 00434 void ProcessBlock(byte *inoutBlock) const 00435 {ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);} 00436 00437 //! block size of the cipher in bytes 00438 virtual unsigned int BlockSize() const =0; 00439 00440 //! block pointers must be divisible by this 00441 virtual unsigned int BlockAlignment() const {return 4;} 00442 00443 //! returns true if this is a permutation (i.e. there is an inverse transformation) 00444 virtual bool IsPermutation() const {return true;} 00445 00446 //! returns true if this is an encryption object 00447 virtual bool IsForwardTransformation() const =0; 00448 00449 //! return number of blocks that can be processed in parallel, for bit-slicing implementations 00450 virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;} 00451 00452 //! encrypt or decrypt multiple blocks, for bit-slicing implementations 00453 virtual void ProcessAndXorMultipleBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, unsigned int numberOfBlocks) const; 00454 }; 00455 00456 //! interface for the data processing part of stream ciphers 00457 00458 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm 00459 { 00460 public: 00461 //! return a reference to this object, 00462 /*! This function is useful for passing a temporary StreamTransformation object to a 00463 function that takes a non-const reference. */ 00464 StreamTransformation& Ref() {return *this;} 00465 00466 //! returns block size, if input must be processed in blocks, otherwise 1 00467 virtual unsigned int MandatoryBlockSize() const {return 1;} 00468 00469 //! returns the input block size that is most efficient for this cipher 00470 /*! \note optimal input length is n * OptimalBlockSize() - GetOptimalBlockSizeUsed() for any n > 0 */ 00471 virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();} 00472 //! returns how much of the current block is used up 00473 virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;} 00474 00475 //! returns how input should be aligned for optimal performance 00476 virtual unsigned int OptimalDataAlignment() const {return 1;} 00477 00478 //! encrypt or decrypt an array of bytes of specified length 00479 /*! \note either inString == outString, or they don't overlap */ 00480 virtual void ProcessData(byte *outString, const byte *inString, unsigned int length) =0; 00481 00482 //! for ciphers where the last block of data is special, encrypt or decrypt the last block of data 00483 /*! For now the only use of this function is for CBC-CTS mode. */ 00484 virtual void ProcessLastBlock(byte *outString, const byte *inString, unsigned int length); 00485 //! returns the minimum size of the last block, 0 indicating the last block is not special 00486 virtual unsigned int MinLastBlockSize() const {return 0;} 00487 00488 //! same as ProcessData(inoutString, inoutString, length) 00489 inline void ProcessString(byte *inoutString, unsigned int length) 00490 {ProcessData(inoutString, inoutString, length);} 00491 //! same as ProcessData(outString, inString, length) 00492 inline void ProcessString(byte *outString, const byte *inString, unsigned int length) 00493 {ProcessData(outString, inString, length);} 00494 //! implemented as {ProcessData(&input, &input, 1); return input;} 00495 inline byte ProcessByte(byte input) 00496 {ProcessData(&input, &input, 1); return input;} 00497 00498 //! returns whether this cipher supports random access 00499 virtual bool IsRandomAccess() const =0; 00500 //! for random access ciphers, seek to an absolute position 00501 virtual void Seek(lword n) 00502 { 00503 assert(!IsRandomAccess()); 00504 throw NotImplemented("StreamTransformation: this object doesn't support random access"); 00505 } 00506 00507 //! returns whether this transformation is self-inverting (e.g. xor with a keystream) 00508 virtual bool IsSelfInverting() const =0; 00509 //! returns whether this is an encryption object 00510 virtual bool IsForwardTransformation() const =0; 00511 }; 00512 00513 //! interface for hash functions and data processing part of MACs 00514 00515 /*! HashTransformation objects are stateful. They are created in an initial state, 00516 change state as Update() is called, and return to the initial 00517 state when Final() is called. This interface allows a large message to 00518 be hashed in pieces by calling Update() on each piece followed by 00519 calling Final(). 00520 */ 00521 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm 00522 { 00523 public: 00524 //! process more input 00525 virtual void Update(const byte *input, unsigned int length) =0; 00526 00527 //! request space to write input into 00528 virtual byte * CreateUpdateSpace(unsigned int &size) {size=0; return NULL;} 00529 00530 //! compute hash for current message, then restart for a new message 00531 /*! \pre size of digest == DigestSize(). */ 00532 virtual void Final(byte *digest) 00533 {TruncatedFinal(digest, DigestSize());} 00534 00535 //! discard the current state, and restart with a new message 00536 virtual void Restart() 00537 {TruncatedFinal(NULL, 0);} 00538 00539 //! size of the hash returned by Final() 00540 virtual unsigned int DigestSize() const =0; 00541 00542 //! block size of underlying compression function, or 0 if not block based 00543 virtual unsigned int BlockSize() const {return 0;} 00544 00545 //! input to Update() should have length a multiple of this for optimal speed 00546 virtual unsigned int OptimalBlockSize() const {return 1;} 00547 00548 //! returns how input should be aligned for optimal performance 00549 virtual unsigned int OptimalDataAlignment() const {return 1;} 00550 00551 //! use this if your input is in one piece and you don't want to call Update() and Final() separately 00552 virtual void CalculateDigest(byte *digest, const byte *input, unsigned int length) 00553 {Update(input, length); Final(digest);} 00554 00555 //! verify that digest is a valid digest for the current message, then reinitialize the object 00556 /*! Default implementation is to call Final() and do a bitwise comparison 00557 between its output and digest. */ 00558 virtual bool Verify(const byte *digest) 00559 {return TruncatedVerify(digest, DigestSize());} 00560 00561 //! use this if your input is in one piece and you don't want to call Update() and Verify() separately 00562 virtual bool VerifyDigest(const byte *digest, const byte *input, unsigned int length) 00563 {Update(input, length); return Verify(digest);} 00564 00565 //! truncated version of Final() 00566 virtual void TruncatedFinal(byte *digest, unsigned int digestSize) =0; 00567 00568 //! truncated version of CalculateDigest() 00569 virtual void CalculateTruncatedDigest(byte *digest, unsigned int digestSize, const byte *input, unsigned int length) 00570 {Update(input, length); TruncatedFinal(digest, digestSize);} 00571 00572 //! truncated version of Verify() 00573 virtual bool TruncatedVerify(const byte *digest, unsigned int digestLength); 00574 00575 //! truncated version of VerifyDigest() 00576 virtual bool VerifyTruncatedDigest(const byte *digest, unsigned int digestLength, const byte *input, unsigned int length) 00577 {Update(input, length); return TruncatedVerify(digest, digestLength);} 00578 00579 protected: 00580 void ThrowIfInvalidTruncatedSize(unsigned int size) const; 00581 }; 00582 00583 typedef HashTransformation HashFunction; 00584 00585 template <class T> 00586 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyedTransformation : public T, public SimpleKeyingInterface 00587 { 00588 public: 00589 void ThrowIfInvalidKeyLength(unsigned int length) 00590 {SimpleKeyingInterface::ThrowIfInvalidKeyLength(*this, length);} 00591 }; 00592 00593 #ifdef CRYPTOPP_DOXYGEN_PROCESSING 00594 //! interface for one direction (encryption or decryption) of a block cipher 00595 /*! \note These objects usually should not be used directly. See BlockTransformation for more details. */ 00596 class BlockCipher : public BlockTransformation, public SimpleKeyingInterface {}; 00597 //! interface for one direction (encryption or decryption) of a stream cipher or cipher mode 00598 class SymmetricCipher : public StreamTransformation, public SimpleKeyingInterface {}; 00599 //! interface for message authentication codes 00600 class MessageAuthenticationCode : public HashTransformation, public SimpleKeyingInterface {}; 00601 #else 00602 typedef SimpleKeyedTransformation<BlockTransformation> BlockCipher; 00603 typedef SimpleKeyedTransformation<StreamTransformation> SymmetricCipher; 00604 typedef SimpleKeyedTransformation<HashTransformation> MessageAuthenticationCode; 00605 #endif 00606 00607 CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation<BlockTransformation>; 00608 CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation<StreamTransformation>; 00609 CRYPTOPP_DLL_TEMPLATE_CLASS SimpleKeyedTransformation<HashTransformation>; 00610 00611 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 00612 typedef SymmetricCipher StreamCipher; 00613 #endif 00614 00615 //! interface for random number generators 00616 /*! All return values are uniformly distributed over the range specified. 00617 */ 00618 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm 00619 { 00620 public: 00621 //! generate new random byte and return it 00622 virtual byte GenerateByte() =0; 00623 00624 //! generate new random bit and return it 00625 /*! Default implementation is to call GenerateByte() and return its parity. */ 00626 virtual unsigned int GenerateBit(); 00627 00628 //! generate a random 32 bit word in the range min to max, inclusive 00629 virtual word32 GenerateWord32(word32 a=0, word32 b=0xffffffffL); 00630 00631 //! generate random array of bytes 00632 /*! Default implementation is to call GenerateByte() size times. */ 00633 virtual void GenerateBlock(byte *output, unsigned int size); 00634 00635 //! generate and discard n bytes 00636 /*! Default implementation is to call GenerateByte() n times. */ 00637 virtual void DiscardBytes(unsigned int n); 00638 00639 //! randomly shuffle the specified array, resulting permutation is uniformly distributed 00640 template <class IT> void Shuffle(IT begin, IT end) 00641 { 00642 for (; begin != end; ++begin) 00643 std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1)); 00644 } 00645 00646 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 00647 byte GetByte() {return GenerateByte();} 00648 unsigned int GetBit() {return GenerateBit();} 00649 word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);} 00650 word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);} 00651 void GetBlock(byte *output, unsigned int size) {GenerateBlock(output, size);} 00652 #endif 00653 }; 00654 00655 //! returns a reference that can be passed to functions that ask for a RNG but doesn't actually use it 00656 CRYPTOPP_DLL RandomNumberGenerator & NullRNG(); 00657 00658 class WaitObjectContainer; 00659 00660 //! interface for objects that you can wait for 00661 00662 class CRYPTOPP_NO_VTABLE Waitable 00663 { 00664 public: 00665 //! maximum number of wait objects that this object can return 00666 virtual unsigned int GetMaxWaitObjectCount() const =0; 00667 //! put wait objects into container 00668 virtual void GetWaitObjects(WaitObjectContainer &container) =0; 00669 //! wait on this object 00670 /*! same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container */ 00671 bool Wait(unsigned long milliseconds); 00672 }; 00673 00674 //! interface for buffered transformations 00675 00676 /*! BufferedTransformation is a generalization of BlockTransformation, 00677 StreamTransformation, and HashTransformation. 00678 00679 A buffered transformation is an object that takes a stream of bytes 00680 as input (this may be done in stages), does some computation on them, and 00681 then places the result into an internal buffer for later retrieval. Any 00682 partial result already in the output buffer is not modified by further 00683 input. 00684 00685 If a method takes a "blocking" parameter, and you 00686 pass "false" for it, the method will return before all input has been processed if 00687 the input cannot be processed without waiting (for network buffers to become available, for example). 00688 In this case the method will return true 00689 or a non-zero integer value. When this happens you must continue to call the method with the same 00690 parameters until it returns false or zero, before calling any other method on it or 00691 attached BufferedTransformation. The integer return value in this case is approximately 00692 the number of bytes left to be processed, and can be used to implement a progress bar. 00693 00694 For functions that take a "propagation" parameter, propagation != 0 means pass on the signal to attached 00695 BufferedTransformation objects, with propagation decremented at each step until it reaches 0. 00696 -1 means unlimited propagation. 00697 00698 \nosubgrouping 00699 */ 00700 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable 00701 { 00702 public: 00703 // placed up here for CW8 00704 static const std::string NULL_CHANNEL; // the empty string "" 00705 00706 BufferedTransformation() : Algorithm(false) {} 00707 00708 //! return a reference to this object 00709 /*! This function is useful for passing a temporary BufferedTransformation object to a 00710 function that takes a non-const reference. */ 00711 BufferedTransformation& Ref() {return *this;} 00712 00713 //! \name INPUT 00714 //@{ 00715 //! input a byte for processing 00716 unsigned int Put(byte inByte, bool blocking=true) 00717 {return Put(&inByte, 1, blocking);} 00718 //! input multiple bytes 00719 unsigned int Put(const byte *inString, unsigned int length, bool blocking=true) 00720 {return Put2(inString, length, 0, blocking);} 00721 00722 //! input a 16-bit word 00723 unsigned int PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 00724 //! input a 32-bit word 00725 unsigned int PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 00726 00727 //! request space which can be written into by the caller, and then used as input to Put() 00728 /*! \param size is requested size (as a hint) for input, and size of the returned space for output */ 00729 /*! \note The purpose of this method is to help avoid doing extra memory allocations. */ 00730 virtual byte * CreatePutSpace(unsigned int &size) {size=0; return NULL;} 00731 00732 virtual bool CanModifyInput() const {return false;} 00733 00734 //! input multiple bytes that may be modified by callee 00735 unsigned int PutModifiable(byte *inString, unsigned int length, bool blocking=true) 00736 {return PutModifiable2(inString, length, 0, blocking);} 00737 00738 bool MessageEnd(int propagation=-1, bool blocking=true) 00739 {return !!Put2(NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);} 00740 unsigned int PutMessageEnd(const byte *inString, unsigned int length, int propagation=-1, bool blocking=true) 00741 {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);} 00742 00743 //! input multiple bytes for blocking or non-blocking processing 00744 /*! \param messageEnd means how many filters to signal MessageEnd to, including this one */ 00745 virtual unsigned int Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking) =0; 00746 //! input multiple bytes that may be modified by callee for blocking or non-blocking processing 00747 /*! \param messageEnd means how many filters to signal MessageEnd to, including this one */ 00748 virtual unsigned int PutModifiable2(byte *inString, unsigned int length, int messageEnd, bool blocking) 00749 {return Put2(inString, length, messageEnd, blocking);} 00750 00751 //! thrown by objects that have not implemented nonblocking input processing 00752 struct BlockingInputOnly : public NotImplemented 00753 {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}}; 00754 //@} 00755 00756 //! \name WAITING 00757 //@{ 00758 unsigned int GetMaxWaitObjectCount() const; 00759 void GetWaitObjects(WaitObjectContainer &container); 00760 //@} 00761 00762 //! \name SIGNALS 00763 //@{ 00764 virtual void IsolatedInitialize(const NameValuePairs &parameters) {throw NotImplemented("BufferedTransformation: this object can't be reinitialized");} 00765 virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0; 00766 virtual bool IsolatedMessageSeriesEnd(bool blocking) {return false;} 00767 00768 //! initialize or reinitialize this object 00769 virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1); 00770 //! flush buffered input and/or output 00771 /*! \param hardFlush is used to indicate whether all data should be flushed 00772 \note Hard flushes must be used with care. It means try to process and output everything, even if 00773 there may not be enough data to complete the action. For example, hard flushing a HexDecoder would 00774 cause an error if you do it after inputing an odd number of hex encoded characters. 00775 For some types of filters, for example ZlibDecompressor, hard flushes can only 00776 be done at "synchronization points". These synchronization points are positions in the data 00777 stream that are created by hard flushes on the corresponding reverse filters, in this 00778 example ZlibCompressor. This is useful when zlib compressed data is moved across a 00779 network in packets and compression state is preserved across packets, as in the ssh2 protocol. 00780 */ 00781 virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true); 00782 //! mark end of a series of messages 00783 /*! There should be a MessageEnd immediately before MessageSeriesEnd. */ 00784 virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true); 00785 00786 //! set propagation of automatically generated and transferred signals 00787 /*! propagation == 0 means do not automaticly generate signals */ 00788 virtual void SetAutoSignalPropagation(int propagation) {} 00789 00790 //! 00791 virtual int GetAutoSignalPropagation() const {return 0;} 00792 public: 00793 00794 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 00795 void Close() {MessageEnd();} 00796 #endif 00797 //@} 00798 00799 //! \name RETRIEVAL OF ONE MESSAGE 00800 //@{ 00801 //! returns number of bytes that is currently ready for retrieval 00802 /*! All retrieval functions return the actual number of bytes 00803 retrieved, which is the lesser of the request number and 00804 MaxRetrievable(). */ 00805 virtual unsigned long MaxRetrievable() const; 00806 00807 //! returns whether any bytes are currently ready for retrieval 00808 virtual bool AnyRetrievable() const; 00809 00810 //! try to retrieve a single byte 00811 virtual unsigned int Get(byte &outByte); 00812 //! try to retrieve multiple bytes 00813 virtual unsigned int Get(byte *outString, unsigned int getMax); 00814 00815 //! peek at the next byte without removing it from the output buffer 00816 virtual unsigned int Peek(byte &outByte) const; 00817 //! peek at multiple bytes without removing them from the output buffer 00818 virtual unsigned int Peek(byte *outString, unsigned int peekMax) const; 00819 00820 //! try to retrieve a 16-bit word 00821 unsigned int GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER); 00822 //! try to retrieve a 32-bit word 00823 unsigned int GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER); 00824 00825 //! try to peek at a 16-bit word 00826 unsigned int PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER); 00827 //! try to peek at a 32-bit word 00828 unsigned int PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER); 00829 00830 //! move transferMax bytes of the buffered output to target as input 00831 unsigned long TransferTo(BufferedTransformation &target, unsigned long transferMax=ULONG_MAX, const std::string &channel=NULL_CHANNEL) 00832 {TransferTo2(target, transferMax, channel); return transferMax;} 00833 00834 //! discard skipMax bytes from the output buffer 00835 virtual unsigned long Skip(unsigned long skipMax=ULONG_MAX); 00836 00837 //! copy copyMax bytes of the buffered output to target as input 00838 unsigned long CopyTo(BufferedTransformation &target, unsigned long copyMax=ULONG_MAX, const std::string &channel=NULL_CHANNEL) const 00839 {return CopyRangeTo(target, 0, copyMax, channel);} 00840 00841 //! copy copyMax bytes of the buffered output, starting at position (relative to current position), to target as input 00842 unsigned long CopyRangeTo(BufferedTransformation &target, unsigned long position, unsigned long copyMax=ULONG_MAX, const std::string &channel=NULL_CHANNEL) const 00843 {unsigned long i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;} 00844 00845 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 00846 unsigned long MaxRetrieveable() const {return MaxRetrievable();} 00847 #endif 00848 //@} 00849 00850 //! \name RETRIEVAL OF MULTIPLE MESSAGES 00851 //@{ 00852 //! 00853 virtual unsigned long TotalBytesRetrievable() const; 00854 //! number of times MessageEnd() has been received minus messages retrieved or skipped 00855 virtual unsigned int NumberOfMessages() const; 00856 //! returns true if NumberOfMessages() > 0 00857 virtual bool AnyMessages() const; 00858 //! start retrieving the next message 00859 /*! 00860 Returns false if no more messages exist or this message 00861 is not completely retrieved. 00862 */ 00863 virtual bool GetNextMessage(); 00864 //! skip count number of messages 00865 virtual unsigned int SkipMessages(unsigned int count=UINT_MAX); 00866 //! 00867 unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=NULL_CHANNEL) 00868 {TransferMessagesTo2(target, count, channel); return count;} 00869 //! 00870 unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=NULL_CHANNEL) const; 00871 00872 //! 00873 virtual void SkipAll(); 00874 //! 00875 void TransferAllTo(BufferedTransformation &target, const std::string &channel=NULL_CHANNEL) 00876 {TransferAllTo2(target, channel);} 00877 //! 00878 void CopyAllTo(BufferedTransformation &target, const std::string &channel=NULL_CHANNEL) const; 00879 00880 virtual bool GetNextMessageSeries() {return false;} 00881 virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();} 00882 virtual unsigned int NumberOfMessageSeries() const {return 0;} 00883 //@} 00884 00885 //! \name NON-BLOCKING TRANSFER OF OUTPUT 00886 //@{ 00887 virtual unsigned int TransferTo2(BufferedTransformation &target, unsigned long &byteCount, const std::string &channel=NULL_CHANNEL, bool blocking=true) =0; 00888 virtual unsigned int CopyRangeTo2(BufferedTransformation &target, unsigned long &begin, unsigned long end=ULONG_MAX, const std::string &channel=NULL_CHANNEL, bool blocking=true) const =0; 00889 unsigned int TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=NULL_CHANNEL, bool blocking=true); 00890 unsigned int TransferAllTo2(BufferedTransformation &target, const std::string &channel=NULL_CHANNEL, bool blocking=true); 00891 //@} 00892 00893 //! \name CHANNELS 00894 //@{ 00895 struct NoChannelSupport : public NotImplemented 00896 {NoChannelSupport() : NotImplemented("BufferedTransformation: this object doesn't support multiple channels") {}}; 00897 00898 unsigned int ChannelPut(const std::string &channel, byte inByte, bool blocking=true) 00899 {return ChannelPut(channel, &inByte, 1, blocking);} 00900 unsigned int ChannelPut(const std::string &channel, const byte *inString, unsigned int length, bool blocking=true) 00901 {return ChannelPut2(channel, inString, length, 0, blocking);} 00902 00903 unsigned int ChannelPutModifiable(const std::string &channel, byte *inString, unsigned int length, bool blocking=true) 00904 {return ChannelPutModifiable2(channel, inString, length, 0, blocking);} 00905 00906 unsigned int ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 00907 unsigned int ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 00908 00909 bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true) 00910 {return !!ChannelPut2(channel, NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);} 00911 unsigned int ChannelPutMessageEnd(const std::string &channel, const byte *inString, unsigned int length, int propagation=-1, bool blocking=true) 00912 {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);} 00913 00914 virtual byte * ChannelCreatePutSpace(const std::string &channel, unsigned int &size); 00915 00916 virtual unsigned int ChannelPut2(const std::string &channel, const byte *begin, unsigned int length, int messageEnd, bool blocking); 00917 virtual unsigned int ChannelPutModifiable2(const std::string &channel, byte *begin, unsigned int length, int messageEnd, bool blocking); 00918 00919 virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true); 00920 virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true); 00921 00922 virtual void SetRetrievalChannel(const std::string &channel); 00923 //@} 00924 00925 //! \name ATTACHMENT 00926 /*! Some BufferedTransformation objects (e.g. Filter objects) 00927 allow other BufferedTransformation objects to be attached. When 00928 this is done, the first object instead of buffering its output, 00929 sents that output to the attached object as input. The entire 00930 attachment chain is deleted when the anchor object is destructed. 00931 */ 00932 //@{ 00933 //! returns whether this object allows attachment 00934 virtual bool Attachable() {return false;} 00935 //! returns the object immediately attached to this object or NULL for no attachment 00936 virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;} 00937 //! 00938 virtual const BufferedTransformation *AttachedTransformation() const 00939 {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();} 00940 //! delete the current attachment chain and replace it with newAttachment 00941 virtual void Detach(BufferedTransformation *newAttachment = 0) 00942 {assert(!Attachable()); throw NotImplemented("BufferedTransformation: this object is not attachable");} 00943 //! add newAttachment to the end of attachment chain 00944 virtual void Attach(BufferedTransformation *newAttachment); 00945 //@} 00946 00947 protected: 00948 static int DecrementPropagation(int propagation) 00949 {return propagation != 0 ? propagation - 1 : 0;} 00950 }; 00951 00952 //! returns a reference to a BufferedTransformation object that discards all input 00953 BufferedTransformation & TheBitBucket(); 00954 00955 //! interface for crypto material, such as public and private keys, and crypto parameters 00956 00957 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs 00958 { 00959 public: 00960 //! exception thrown when invalid crypto material is detected 00961 class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat 00962 { 00963 public: 00964 explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {} 00965 }; 00966 00967 //! assign values from source to this object 00968 /*! \note This function can be used to create a public key from a private key. */ 00969 virtual void AssignFrom(const NameValuePairs &source) =0; 00970 00971 //! check this object for errors 00972 /*! \param level denotes the level of thoroughness: 00973 0 - using this object won't cause a crash or exception (rng is ignored) 00974 1 - this object will probably function (encrypt, sign, etc.) correctly (but may not check for weak keys and such) 00975 2 - make sure this object will function correctly, and do reasonable security checks 00976 3 - do checks that may take a long time 00977 \return true if the tests pass */ 00978 virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0; 00979 00980 //! throws InvalidMaterial if this object fails Validate() test 00981 virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const 00982 {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");} 00983 00984 // virtual std::vector<std::string> GetSupportedFormats(bool includeSaveOnly=false, bool includeLoadOnly=false); 00985 00986 //! save key into a BufferedTransformation 00987 virtual void Save(BufferedTransformation &bt) const 00988 {throw NotImplemented("CryptoMaterial: this object does not support saving");} 00989 00990 //! load key from a BufferedTransformation 00991 /*! \throws KeyingErr if decode fails 00992 \note Generally does not check that the key is valid. 00993 Call ValidateKey() or ThrowIfInvalidKey() to check that. */ 00994 virtual void Load(BufferedTransformation &bt) 00995 {throw NotImplemented("CryptoMaterial: this object does not support loading");} 00996 00997 //! \return whether this object supports precomputation 00998 virtual bool SupportsPrecomputation() const {return false;} 00999 //! do precomputation 01000 /*! The exact semantics of Precompute() is varies, but 01001 typically it means calculate a table of n objects 01002 that can be used later to speed up computation. */ 01003 virtual void Precompute(unsigned int n) 01004 {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} 01005 //! retrieve previously saved precomputation 01006 virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation) 01007 {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} 01008 //! save precomputation for later use 01009 virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const 01010 {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} 01011 01012 // for internal library use 01013 void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);} 01014 }; 01015 01016 //! interface for generatable crypto material, such as private keys and crypto parameters 01017 01018 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial 01019 { 01020 public: 01021 //! generate a random key or crypto parameters 01022 /*! \throws KeyingErr if algorithm parameters are invalid, or if a key can't be generated 01023 (e.g., if this is a public key object) */ 01024 virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs) 01025 {throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");} 01026 01027 //! calls the above function with a NameValuePairs object that just specifies "KeySize" 01028 void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize); 01029 }; 01030 01031 //! interface for public keys 01032 01033 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial 01034 { 01035 }; 01036 01037 //! interface for private keys 01038 01039 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial 01040 { 01041 }; 01042 01043 //! interface for crypto prameters 01044 01045 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial 01046 { 01047 }; 01048 01049 //! interface for asymmetric algorithms 01050 01051 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm 01052 { 01053 public: 01054 //! returns a reference to the crypto material used by this object 01055 virtual CryptoMaterial & AccessMaterial() =0; 01056 //! returns a const reference to the crypto material used by this object 01057 virtual const CryptoMaterial & GetMaterial() const =0; 01058 01059 //! for backwards compatibility, calls AccessMaterial().Load(bt) 01060 void BERDecode(BufferedTransformation &bt) 01061 {AccessMaterial().Load(bt);} 01062 //! for backwards compatibility, calls GetMaterial().Save(bt) 01063 void DEREncode(BufferedTransformation &bt) const 01064 {GetMaterial().Save(bt);} 01065 }; 01066 01067 //! interface for asymmetric algorithms using public keys 01068 01069 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm 01070 { 01071 public: 01072 // VC60 workaround: no co-variant return type 01073 CryptoMaterial & AccessMaterial() {return AccessPublicKey();} 01074 const CryptoMaterial & GetMaterial() const {return GetPublicKey();} 01075 01076 virtual PublicKey & AccessPublicKey() =0; 01077 virtual const PublicKey & GetPublicKey() const {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();} 01078 }; 01079 01080 //! interface for asymmetric algorithms using private keys 01081 01082 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm 01083 { 01084 public: 01085 CryptoMaterial & AccessMaterial() {return AccessPrivateKey();} 01086 const CryptoMaterial & GetMaterial() const {return GetPrivateKey();} 01087 01088 virtual PrivateKey & AccessPrivateKey() =0; 01089 virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();} 01090 }; 01091 01092 //! interface for key agreement algorithms 01093 01094 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm 01095 { 01096 public: 01097 CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();} 01098 const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();} 01099 01100 virtual CryptoParameters & AccessCryptoParameters() =0; 01101 virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();} 01102 }; 01103 01104 //! interface for public-key encryptors and decryptors 01105 01106 /*! This class provides an interface common to encryptors and decryptors 01107 for querying their plaintext and ciphertext lengths. 01108 */ 01109 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem 01110 { 01111 public: 01112 virtual ~PK_CryptoSystem() {} 01113 01114 //! maximum length of plaintext for a given ciphertext length 01115 /*! \note This function returns 0 if ciphertextLength is not valid (too long or too short). */ 01116 virtual unsigned int MaxPlaintextLength(unsigned int ciphertextLength) const =0; 01117 01118 //! calculate length of ciphertext given length of plaintext 01119 /*! \note This function returns 0 if plaintextLength is not valid (too long). */ 01120 virtual unsigned int CiphertextLength(unsigned int plaintextLength) const =0; 01121 01122 //! this object supports the use of the parameter with the given name 01123 /*! some possible parameter names: EncodingParameters, KeyDerivationParameters */ 01124 virtual bool ParameterSupported(const char *name) const =0; 01125 01126 //! return fixed ciphertext length, if one exists, otherwise return 0 01127 /*! \note "Fixed" here means length of ciphertext does not depend on length of plaintext. 01128 It usually does depend on the key length. */ 01129 virtual unsigned int FixedCiphertextLength() const {return 0;} 01130 01131 //! return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0 01132 virtual unsigned int FixedMaxPlaintextLength() const {return 0;} 01133 01134 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01135 unsigned int MaxPlainTextLength(unsigned int cipherTextLength) const {return MaxPlaintextLength(cipherTextLength);} 01136 unsigned int CipherTextLength(unsigned int plainTextLength) const {return CiphertextLength(plainTextLength);} 01137 #endif 01138 }; 01139 01140 //! interface for public-key encryptors 01141 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : virtual public PK_CryptoSystem, public PublicKeyAlgorithm 01142 { 01143 public: 01144 //! exception thrown when trying to encrypt plaintext of invalid length 01145 class CRYPTOPP_DLL InvalidPlaintextLength : public Exception 01146 { 01147 public: 01148 InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {} 01149 }; 01150 01151 //! encrypt a byte string 01152 /*! \pre CiphertextLength(plaintextLength) != 0 (i.e., plaintext isn't too long) 01153 \pre size of ciphertext == CiphertextLength(plaintextLength) 01154 */ 01155 virtual void Encrypt(RandomNumberGenerator &rng, 01156 const byte *plaintext, unsigned int plaintextLength, 01157 byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0; 01158 01159 //! create a new encryption filter 01160 /*! \note The caller is responsible for deleting the returned pointer. 01161 \note Encoding parameters should be passed in the "EP" channel. 01162 */ 01163 virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, 01164 BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const; 01165 }; 01166 01167 //! interface for public-key decryptors 01168 01169 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : virtual public PK_CryptoSystem, public PrivateKeyAlgorithm 01170 { 01171 public: 01172 //! decrypt a byte string, and return the length of plaintext 01173 /*! \pre size of plaintext == MaxPlaintextLength(ciphertextLength) bytes. 01174 \return the actual length of the plaintext, indication that decryption failed. 01175 */ 01176 virtual DecodingResult Decrypt(RandomNumberGenerator &rng, 01177 const byte *ciphertext, unsigned int ciphertextLength, 01178 byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0; 01179 01180 //! create a new decryption filter 01181 /*! \note caller is responsible for deleting the returned pointer 01182 */ 01183 virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, 01184 BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const; 01185 01186 //! decrypt a fixed size ciphertext 01187 DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const 01188 {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);} 01189 }; 01190 01191 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01192 typedef PK_CryptoSystem PK_FixedLengthCryptoSystem; 01193 typedef PK_Encryptor PK_FixedLengthEncryptor; 01194 typedef PK_Decryptor PK_FixedLengthDecryptor; 01195 #endif 01196 01197 //! interface for public-key signers and verifiers 01198 01199 /*! This class provides an interface common to signers and verifiers 01200 for querying scheme properties. 01201 */ 01202 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme 01203 { 01204 public: 01205 //! 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 01206 class CRYPTOPP_DLL InvalidKeyLength : public Exception 01207 { 01208 public: 01209 InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {} 01210 }; 01211 01212 //! 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 01213 class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength 01214 { 01215 public: 01216 KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {} 01217 }; 01218 01219 virtual ~PK_SignatureScheme() {} 01220 01221 //! signature length if it only depends on the key, otherwise 0 01222 virtual unsigned int SignatureLength() const =0; 01223 01224 //! maximum signature length produced for a given length of recoverable message part 01225 virtual unsigned int MaxSignatureLength(unsigned int recoverablePartLength = 0) const {return SignatureLength();} 01226 01227 //! length of longest message that can be recovered, or 0 if this signature scheme does not support message recovery 01228 virtual unsigned int MaxRecoverableLength() const =0; 01229 01230 //! length of longest message that can be recovered from a signature of given length, or 0 if this signature scheme does not support message recovery 01231 virtual unsigned int MaxRecoverableLengthFromSignatureLength(unsigned int signatureLength) const =0; 01232 01233 //! requires a random number generator to sign 01234 /*! if this returns false, NullRNG() can be passed to functions that take RandomNumberGenerator & */ 01235 virtual bool IsProbabilistic() const =0; 01236 01237 //! whether or not a non-recoverable message part can be signed 01238 virtual bool AllowNonrecoverablePart() const =0; 01239 01240 //! if this function returns true, during verification you must input the signature before the message, otherwise you can input it at anytime */ 01241 virtual bool SignatureUpfront() const {return false;} 01242 01243 //! whether you must input the recoverable part before the non-recoverable part during signing 01244 virtual bool RecoverablePartFirst() const =0; 01245 }; 01246 01247 //! interface for accumulating messages to be signed or verified 01248 /*! Only Update() should be called 01249 on this class. No other functions inherited from HashTransformation should be called. 01250 */ 01251 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation 01252 { 01253 public: 01254 //! should not be called on PK_MessageAccumulator 01255 unsigned int DigestSize() const 01256 {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");} 01257 //! should not be called on PK_MessageAccumulator 01258 void TruncatedFinal(byte *digest, unsigned int digestSize) 01259 {throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");} 01260 }; 01261 01262 //! interface for public-key signers 01263 01264 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm 01265 { 01266 public: 01267 //! create a new HashTransformation to accumulate the message to be signed 01268 virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0; 01269 01270 virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, unsigned int recoverableMessageLength) const =0; 01271 01272 //! sign and delete messageAccumulator (even in case of exception thrown) 01273 /*! \pre size of signature == MaxSignatureLength() 01274 \return actual signature length 01275 */ 01276 virtual unsigned int Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const; 01277 01278 //! sign and restart messageAccumulator 01279 /*! \pre size of signature == MaxSignatureLength() 01280 \return actual signature length 01281 */ 01282 virtual unsigned int SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0; 01283 01284 //! sign a message 01285 /*! \pre size of signature == MaxSignatureLength() 01286 \return actual signature length 01287 */ 01288 virtual unsigned int SignMessage(RandomNumberGenerator &rng, const byte *message, unsigned int messageLen, byte *signature) const; 01289 01290 //! sign a recoverable message 01291 /*! \pre size of signature == MaxSignatureLength(recoverableMessageLength) 01292 \return actual signature length 01293 */ 01294 virtual unsigned int SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, unsigned int recoverableMessageLength, 01295 const byte *nonrecoverableMessage, unsigned int nonrecoverableMessageLength, byte *signature) const; 01296 }; 01297 01298 //! interface for public-key signature verifiers 01299 /*! The Recover* functions throw NotImplemented if the signature scheme does not support 01300 message recovery. 01301 The Verify* functions throw InvalidDataFormat if the scheme does support message 01302 recovery and the signature contains a non-empty recoverable message part. The 01303 Recovery* functions should be used in that case. 01304 */ 01305 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm 01306 { 01307 public: 01308 //! create a new HashTransformation to accumulate the message to be verified 01309 virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0; 01310 01311 //! input signature into a message accumulator 01312 virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, unsigned int signatureLength) const =0; 01313 01314 //! check whether messageAccumulator contains a valid signature and message, and delete messageAccumulator (even in case of exception thrown) 01315 virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const; 01316 01317 //! check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator 01318 virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0; 01319 01320 //! check whether input signature is a valid signature for input message 01321 virtual bool VerifyMessage(const byte *message, unsigned int messageLen, 01322 const byte *signature, unsigned int signatureLength) const; 01323 01324 //! recover a message from its signature 01325 /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength) 01326 */ 01327 virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const; 01328 01329 //! recover a message from its signature 01330 /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength) 01331 */ 01332 virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0; 01333 01334 //! recover a message from its signature 01335 /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength) 01336 */ 01337 virtual DecodingResult RecoverMessage(byte *recoveredMessage, 01338 const byte *nonrecoverableMessage, unsigned int nonrecoverableMessageLength, 01339 const byte *signature, unsigned int signatureLength) const; 01340 }; 01341 01342 //! interface for domains of simple key agreement protocols 01343 01344 /*! A key agreement domain is a set of parameters that must be shared 01345 by two parties in a key agreement protocol, along with the algorithms 01346 for generating key pairs and deriving agreed values. 01347 */ 01348 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm 01349 { 01350 public: 01351 //! return length of agreed value produced 01352 virtual unsigned int AgreedValueLength() const =0; 01353 //! return length of private keys in this domain 01354 virtual unsigned int PrivateKeyLength() const =0; 01355 //! return length of public keys in this domain 01356 virtual unsigned int PublicKeyLength() const =0; 01357 //! generate private key 01358 /*! \pre size of privateKey == PrivateKeyLength() */ 01359 virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 01360 //! generate public key 01361 /*! \pre size of publicKey == PublicKeyLength() */ 01362 virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 01363 //! generate private/public key pair 01364 /*! \note equivalent to calling GeneratePrivateKey() and then GeneratePublicKey() */ 01365 virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 01366 //! derive agreed value from your private key and couterparty's public key, return false in case of failure 01367 /*! \note If you have previously validated the public key, use validateOtherPublicKey=false to save time. 01368 \pre size of agreedValue == AgreedValueLength() 01369 \pre length of privateKey == PrivateKeyLength() 01370 \pre length of otherPublicKey == PublicKeyLength() 01371 */ 01372 virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0; 01373 01374 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01375 bool ValidateDomainParameters(RandomNumberGenerator &rng) const 01376 {return GetCryptoParameters().Validate(rng, 2);} 01377 #endif 01378 }; 01379 01380 //! interface for domains of authenticated key agreement protocols 01381 01382 /*! In an authenticated key agreement protocol, each party has two 01383 key pairs. The long-lived key pair is called the static key pair, 01384 and the short-lived key pair is called the ephemeral key pair. 01385 */ 01386 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm 01387 { 01388 public: 01389 //! return length of agreed value produced 01390 virtual unsigned int AgreedValueLength() const =0; 01391 01392 //! return length of static private keys in this domain 01393 virtual unsigned int StaticPrivateKeyLength() const =0; 01394 //! return length of static public keys in this domain 01395 virtual unsigned int StaticPublicKeyLength() const =0; 01396 //! generate static private key 01397 /*! \pre size of privateKey == PrivateStaticKeyLength() */ 01398 virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 01399 //! generate static public key 01400 /*! \pre size of publicKey == PublicStaticKeyLength() */ 01401 virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 01402 //! generate private/public key pair 01403 /*! \note equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey() */ 01404 virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 01405 01406 //! return length of ephemeral private keys in this domain 01407 virtual unsigned int EphemeralPrivateKeyLength() const =0; 01408 //! return length of ephemeral public keys in this domain 01409 virtual unsigned int EphemeralPublicKeyLength() const =0; 01410 //! generate ephemeral private key 01411 /*! \pre size of privateKey == PrivateEphemeralKeyLength() */ 01412 virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 01413 //! generate ephemeral public key 01414 /*! \pre size of publicKey == PublicEphemeralKeyLength() */ 01415 virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 01416 //! generate private/public key pair 01417 /*! \note equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() */ 01418 virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 01419 01420 //! derive agreed value from your private keys and couterparty's public keys, return false in case of failure 01421 /*! \note The ephemeral public key will always be validated. 01422 If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time. 01423 \pre size of agreedValue == AgreedValueLength() 01424 \pre length of staticPrivateKey == StaticPrivateKeyLength() 01425 \pre length of ephemeralPrivateKey == EphemeralPrivateKeyLength() 01426 \pre length of staticOtherPublicKey == StaticPublicKeyLength() 01427 \pre length of ephemeralOtherPublicKey == EphemeralPublicKeyLength() 01428 */ 01429 virtual bool Agree(byte *agreedValue, 01430 const byte *staticPrivateKey, const byte *ephemeralPrivateKey, 01431 const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey, 01432 bool validateStaticOtherPublicKey=true) const =0; 01433 01434 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01435 bool ValidateDomainParameters(RandomNumberGenerator &rng) const 01436 {return GetCryptoParameters().Validate(rng, 2);} 01437 #endif 01438 }; 01439 01440 // interface for password authenticated key agreement protocols, not implemented yet 01441 #if 0 01442 //! interface for protocol sessions 01443 /*! The methods should be called in the following order: 01444 01445 InitializeSession(rng, parameters); // or call initialize method in derived class 01446 while (true) 01447 { 01448 if (OutgoingMessageAvailable()) 01449 { 01450 length = GetOutgoingMessageLength(); 01451 GetOutgoingMessage(message); 01452 ; // send outgoing message 01453 } 01454 01455 if (LastMessageProcessed()) 01456 break; 01457 01458 ; // receive incoming message 01459 ProcessIncomingMessage(message); 01460 } 01461 ; // call methods in derived class to obtain result of protocol session 01462 */ 01463 class ProtocolSession 01464 { 01465 public: 01466 //! exception thrown when an invalid protocol message is processed 01467 class ProtocolError : public Exception 01468 { 01469 public: 01470 ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {} 01471 }; 01472 01473 //! exception thrown when a function is called unexpectedly 01474 /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */ 01475 class UnexpectedMethodCall : public Exception 01476 { 01477 public: 01478 UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {} 01479 }; 01480 01481 ProtocolSession() : m_rng(NULL), m_throwOnProtocolError(true), m_validState(false) {} 01482 virtual ~ProtocolSession() {} 01483 01484 virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0; 01485 01486 bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;} 01487 void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;} 01488 01489 bool HasValidState() const {return m_validState;} 01490 01491 virtual bool OutgoingMessageAvailable() const =0; 01492 virtual unsigned int GetOutgoingMessageLength() const =0; 01493 virtual void GetOutgoingMessage(byte *message) =0; 01494 01495 virtual bool LastMessageProcessed() const =0; 01496 virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0; 01497 01498 protected: 01499 void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const; 01500 void CheckAndHandleInvalidState() const; 01501 void SetValidState(bool valid) {m_validState = valid;} 01502 01503 RandomNumberGenerator *m_rng; 01504 01505 private: 01506 bool m_throwOnProtocolError, m_validState; 01507 }; 01508 01509 class KeyAgreementSession : public ProtocolSession 01510 { 01511 public: 01512 virtual unsigned int GetAgreedValueLength() const =0; 01513 virtual void GetAgreedValue(byte *agreedValue) const =0; 01514 }; 01515 01516 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession 01517 { 01518 public: 01519 void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng, 01520 const byte *myId, unsigned int myIdLength, 01521 const byte *counterPartyId, unsigned int counterPartyIdLength, 01522 const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength); 01523 }; 01524 01525 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm 01526 { 01527 public: 01528 //! return whether the domain parameters stored in this object are valid 01529 virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const 01530 {return GetCryptoParameters().Validate(rng, 2);} 01531 01532 virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0; 01533 virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0; 01534 01535 enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8}; 01536 01537 virtual bool IsValidRole(unsigned int role) =0; 01538 virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0; 01539 }; 01540 #endif 01541 01542 //! BER Decode Exception Class, may be thrown during an ASN1 BER decode operation 01543 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument 01544 { 01545 public: 01546 BERDecodeErr() : InvalidArgument("BER decode error") {} 01547 BERDecodeErr(const std::string &s) : InvalidArgument(s) {} 01548 }; 01549 01550 //! interface for encoding and decoding ASN1 objects 01551 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object 01552 { 01553 public: 01554 virtual ~ASN1Object() {} 01555 //! decode this object from a BufferedTransformation, using BER (Basic Encoding Rules) 01556 virtual void BERDecode(BufferedTransformation &bt) =0; 01557 //! encode this object into a BufferedTransformation, using DER (Distinguished Encoding Rules) 01558 virtual void DEREncode(BufferedTransformation &bt) const =0; 01559 //! encode this object into a BufferedTransformation, using BER 01560 /*! this may be useful if DEREncode() would be too inefficient */ 01561 virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);} 01562 }; 01563 01564 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01565 typedef PK_SignatureScheme PK_SignatureSystem; 01566 typedef SimpleKeyAgreementDomain PK_SimpleKeyAgreementDomain; 01567 typedef AuthenticatedKeyAgreementDomain PK_AuthenticatedKeyAgreementDomain; 01568 #endif 01569 01570 NAMESPACE_END 01571 01572 #endif

Generated on Wed Jul 21 19:15:22 2004 for Crypto++ by doxygen 1.3.7-20040704