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

Generated on Fri Aug 27 15:51:03 2004 for Crypto++ by doxygen 1.3.8