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

Generated on Tue Jul 8 23:34:11 2003 for Crypto++ by doxygen 1.3.2