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

Generated on Tue Jun 30 2015 19:07:04 for Crypto++ by  doxygen 1.7.1