- Main Page
- Namespaces
- Classes
- Files

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