00001 // cryptlib.h - written and placed in the public domain by Wei Dai 00002 00003 //! \file cryptlib.h 00004 //! \brief Abstract base classes that provide a uniform interface to this library. 00005 00006 /*! \mainpage Crypto++ Library 5.6.3 API Reference 00007 <dl> 00008 <dt>Abstract Base Classes<dd> 00009 cryptlib.h 00010 <dt>Authenticated Encryption Modes<dd> 00011 CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)" 00012 <dt>Block Ciphers<dd> 00013 \ref Rijndael "AES", Weak::ARC4, Blowfish, BTEA, Camellia, CAST128, CAST256, DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", 00014 \ref DES_XEX3 "DESX", GOST, IDEA, \ref LR "Luby-Rackoff", MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent, 00015 \ref SHACAL2 "SHACAL-2", SHARK, SKIPJACK, 00016 Square, TEA, \ref ThreeWay "3-Way", Twofish, XTEA 00017 <dt>Stream Ciphers<dd> 00018 \ref Panama "Panama-LE", \ref Panama "Panama-BE", Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20 00019 <dt>Hash Functions<dd> 00020 SHA1, SHA224, SHA256, SHA384, SHA512, \ref SHA3 "SHA-3", Tiger, Whirlpool, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, Weak::MD2, Weak::MD4, Weak::MD5 00021 <dt>Non-Cryptographic Checksums<dd> 00022 CRC32, Adler32 00023 <dt>Message Authentication Codes<dd> 00024 VMAC, HMAC, CBC_MAC, CMAC, DMAC, TTMAC, \ref GCM "GCM (GMAC)" 00025 <dt>Random Number Generators<dd> 00026 NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG, 00027 \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)", RDRAND, RDSEED 00028 <dt>Key Derivation and Password-based Cryptography<dd> 00029 HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)", \ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)" 00030 <dt>Public Key Cryptosystems<dd> 00031 DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES 00032 <dt>Public Key Signature Schemes<dd> 00033 DSA2, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, RabinSS, RWSS, ESIGN 00034 <dt>Key Agreement<dd> 00035 DH, DH2, MQV, ECDH, ECMQV, XTR_DH 00036 <dt>Algebraic Structures<dd> 00037 Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver, 00038 ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP 00039 <dt>Secret Sharing and Information Dispersal<dd> 00040 SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery 00041 <dt>Compression<dd> 00042 Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor 00043 <dt>Input Source Classes<dd> 00044 StringSource, ArraySource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource 00045 <dt>Output Sink Classes<dd> 00046 StringSinkTemplate, StringSink, ArraySink, FileSink, SocketSink, WindowsPipeSink, RandomNumberSink 00047 <dt>Filter Wrappers<dd> 00048 StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter 00049 <dt>Binary to Text Encoders and Decoders<dd> 00050 HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder, Base32Decoder 00051 <dt>Wrappers for OS features<dd> 00052 Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer 00053 <dt>FIPS 140 validated cryptography<dd> 00054 fips140.h 00055 </dl> 00056 00057 In the DLL version of Crypto++, only the following implementation class are available. 00058 <dl> 00059 <dt>Block Ciphers<dd> 00060 AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK 00061 <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd> 00062 \ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>", \ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>" 00063 <dt>Hash Functions<dd> 00064 SHA1, SHA224, SHA256, SHA384, SHA512 00065 <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd> 00066 RSASS<PKCS1v15, H>, RSASS<PSS, H>, RSASS_ISO<H>, RWSS<P1363_EMSA2, H>, DSA, ECDSA<ECP, H>, ECDSA<EC2N, H> 00067 <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd> 00068 HMAC<H>, CBC_MAC<DES_EDE2>, CBC_MAC<DES_EDE3>, GCM<AES> 00069 <dt>Random Number Generators<dd> 00070 DefaultAutoSeededRNG (AutoSeededX917RNG<AES>) 00071 <dt>Key Agreement<dd> 00072 DH, DH2 00073 <dt>Public Key Cryptosystems<dd> 00074 RSAES<OAEP<SHA1> > 00075 </dl> 00076 00077 <p>This reference manual is a work in progress. Some classes are lack detailed descriptions. 00078 <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual. 00079 <p>Thanks to Ryan Phillips for providing the Doxygen configuration file 00080 and getting us started on the manual. 00081 */ 00082 00083 #ifndef CRYPTOPP_CRYPTLIB_H 00084 #define CRYPTOPP_CRYPTLIB_H 00085 00086 #include "config.h" 00087 #include "stdcpp.h" 00088 00089 #if CRYPTOPP_MSC_VERSION 00090 # pragma warning(push) 00091 # pragma warning(disable: 4127 4189 4702) 00092 #endif 00093 00094 NAMESPACE_BEGIN(CryptoPP) 00095 00096 // forward declarations 00097 class Integer; 00098 class RandomNumberGenerator; 00099 class BufferedTransformation; 00100 00101 //! \brief Specifies a direction for a cipher to operate 00102 enum CipherDir {ENCRYPTION, DECRYPTION}; 00103 00104 //! \brief Represents infinite time 00105 const unsigned long INFINITE_TIME = ULONG_MAX; 00106 00107 // VC60 workaround: using enums as template parameters causes problems 00108 //! \brief Converts a typename to an enumerated value 00109 template <typename ENUM_TYPE, int VALUE> 00110 struct EnumToType 00111 { 00112 static ENUM_TYPE ToEnum() {return (ENUM_TYPE)VALUE;} 00113 }; 00114 00115 //! \brief Provides the byte ordering 00116 enum ByteOrder {LITTLE_ENDIAN_ORDER = 0, BIG_ENDIAN_ORDER = 1}; 00117 //! \typedef Provides a constant for LittleEndian 00118 typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian; 00119 //! \typedef Provides a constant for BigEndian 00120 typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian; 00121 00122 //! \class Exception 00123 //! \brief Base class for all exceptions thrown by Crypto++ 00124 class CRYPTOPP_DLL Exception : public std::exception 00125 { 00126 public: 00127 //! error types 00128 enum ErrorType { 00129 //! \brief A method was called which was not implemented 00130 NOT_IMPLEMENTED, 00131 //! \brief An invalid argument was detected 00132 INVALID_ARGUMENT, 00133 //! \brief BufferedTransformation received a Flush(true) signal but can't flush buffers 00134 CANNOT_FLUSH, 00135 //! \brief Data integerity check, such as CRC or MAC, failed 00136 DATA_INTEGRITY_CHECK_FAILED, 00137 //! \brief Input data was received that did not conform to expected format 00138 INVALID_DATA_FORMAT, 00139 //! \brief Error reading from input device or writing to output device 00140 IO_ERROR, 00141 //! \brief Some other error occurred not belong to any of the above categories 00142 OTHER_ERROR 00143 }; 00144 00145 //! \brief Construct a new Exception 00146 explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {} 00147 virtual ~Exception() throw() {} 00148 00149 //! \brief Retrieves a C-string describing the exception 00150 const char *what() const throw() {return (m_what.c_str());} 00151 //! \brief Retrieves a string describing the exception 00152 const std::string &GetWhat() const {return m_what;} 00153 //! \brief Sets the error string for the exception 00154 void SetWhat(const std::string &s) {m_what = s;} 00155 //! \brief Retrieves the error type for the exception 00156 ErrorType GetErrorType() const {return m_errorType;} 00157 //! \brief Sets the error type for the exceptions 00158 void SetErrorType(ErrorType errorType) {m_errorType = errorType;} 00159 00160 private: 00161 ErrorType m_errorType; 00162 std::string m_what; 00163 }; 00164 00165 //! \brief An invalid argument was detected 00166 class CRYPTOPP_DLL InvalidArgument : public Exception 00167 { 00168 public: 00169 explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {} 00170 }; 00171 00172 //! \brief Input data was received that did not conform to expected format 00173 class CRYPTOPP_DLL InvalidDataFormat : public Exception 00174 { 00175 public: 00176 explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {} 00177 }; 00178 00179 //! \brief A decryption filter encountered invalid ciphertext 00180 class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat 00181 { 00182 public: 00183 explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {} 00184 }; 00185 00186 //! \brief A method was called which was not implemented 00187 class CRYPTOPP_DLL NotImplemented : public Exception 00188 { 00189 public: 00190 explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {} 00191 }; 00192 00193 //! \brief Flush(true) was called but it can't completely flush its buffers 00194 class CRYPTOPP_DLL CannotFlush : public Exception 00195 { 00196 public: 00197 explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {} 00198 }; 00199 00200 //! \brief The operating system reported an error 00201 class CRYPTOPP_DLL OS_Error : public Exception 00202 { 00203 public: 00204 OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode) 00205 : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {} 00206 ~OS_Error() throw() {} 00207 00208 //! \brief Retrieve the operating system API that reported the error 00209 const std::string & GetOperation() const {return m_operation;} 00210 //! \brief Retrieve the error code returned by the operating system 00211 int GetErrorCode() const {return m_errorCode;} 00212 00213 protected: 00214 std::string m_operation; 00215 int m_errorCode; 00216 }; 00217 00218 //! \class DecodingResult 00219 //! \brief Returns a decoding results 00220 struct CRYPTOPP_DLL DecodingResult 00221 { 00222 //! \brief Constructs a DecodingResult 00223 //! \details isValidCoding is initialized to false and messageLength is initialized to 0. 00224 explicit DecodingResult() : isValidCoding(false), messageLength(0) {} 00225 //! \brief Constructs a DecodingResult 00226 //! \param len the message length 00227 //! \details isValidCoding is initialized to true. 00228 explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {} 00229 00230 //! \brief Compare two DecodingResult 00231 //! \param rhs the other DecodingResult 00232 //! \returns true if both isValidCoding and messageLength are equal, false otherwise 00233 bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;} 00234 //! \brief Compare two DecodingResult 00235 //! \param rhs the other DecodingResult 00236 //! \returns true if either isValidCoding or messageLength is \a not equal, false otherwise 00237 //! \details Returns <tt>!operator==(rhs)</tt>. 00238 bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);} 00239 00240 //! \brief Flag to indicate the decoding is valid 00241 bool isValidCoding; 00242 //! \brief Recovered message length if isValidCoding is true, undefined otherwise 00243 size_t messageLength; 00244 00245 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 00246 operator size_t() const {return isValidCoding ? messageLength : 0;} 00247 #endif 00248 }; 00249 00250 //! \class NameValuePairs 00251 //! \brief Interface for retrieving values given their names 00252 //! \details This class is used to safely pass a variable number of arbitrarily typed arguments to functions 00253 //! and to read values from keys and crypto parameters. 00254 //! \details To obtain an object that implements NameValuePairs for the purpose of parameter 00255 //! passing, use the MakeParameters() function. 00256 //! \details To get a value from NameValuePairs, you need to know the name and the type of the value. 00257 //! Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports. 00258 //! then look at the Name namespace documentation to see what the type of each value is, or 00259 //! alternatively, call GetIntValue() with the value name, and if the type is not int, a 00260 //! ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object. 00261 class CRYPTOPP_NO_VTABLE NameValuePairs 00262 { 00263 public: 00264 virtual ~NameValuePairs() {} 00265 00266 //! \class ValueTypeMismatch 00267 //! \brief Thrown when an unexpected type is encountered 00268 //! \details Exception thrown when trying to retrieve a value using a different type than expected 00269 class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument 00270 { 00271 public: 00272 //! \brief Construct a ValueTypeMismatch 00273 //! \param name the name of the value 00274 //! \param stored the \a actual type of the value stored 00275 //! \param retrieving the \a presumed type of the value retrieved 00276 ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving) 00277 : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'") 00278 , m_stored(stored), m_retrieving(retrieving) {} 00279 00280 //! \brief Provides the stored type 00281 //! \returns the C++ mangled name of the type 00282 const std::type_info & GetStoredTypeInfo() const {return m_stored;} 00283 00284 //! \brief Provides the retrieveing type 00285 //! \returns the C++ mangled name of the type 00286 const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;} 00287 00288 private: 00289 const std::type_info &m_stored; 00290 const std::type_info &m_retrieving; 00291 }; 00292 00293 //! \brief Get a copy of this object or subobject 00294 //! \tparam T class or type 00295 //! \param object reference to a variable that receives the value 00296 template <class T> 00297 bool GetThisObject(T &object) const 00298 { 00299 return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object); 00300 } 00301 00302 //! \brief Get a pointer to this object 00303 //! \tparam T class or type 00304 //! \param ptr reference to a pointer to a variable that receives the value 00305 template <class T> 00306 bool GetThisPointer(T *&ptr) const 00307 { 00308 return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr); 00309 } 00310 00311 //! \brief Get a named value 00312 //! \tparam T class or type 00313 //! \param name the name of the object or value to retrieve 00314 //! \param value reference to a variable that receives the value 00315 //! \returns true if the value was retrieved, false otherwise 00316 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00317 //! GetRequiredParameter() and GetRequiredIntParameter() 00318 template <class T> 00319 bool GetValue(const char *name, T &value) const 00320 { 00321 return GetVoidValue(name, typeid(T), &value); 00322 } 00323 00324 //! \brief Get a named value 00325 //! \tparam T class or type 00326 //! \param name the name of the object or value to retrieve 00327 //! \param defaultValue the default value of the class or type if it does not exist 00328 //! \returns the object or value 00329 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00330 //! GetRequiredParameter() and GetRequiredIntParameter() 00331 template <class T> 00332 T GetValueWithDefault(const char *name, T defaultValue) const 00333 { 00334 T value; 00335 bool result = GetValue(name, value); 00336 // No assert... this recovers from failure 00337 if (result) {return value;} 00338 return defaultValue; 00339 } 00340 00341 //! \brief Get a list of value names that can be retrieved 00342 //! \returns a list of names available to retrieve 00343 //! \details the items in the list are delimited with a colon. 00344 CRYPTOPP_DLL std::string GetValueNames() const 00345 {std::string result; GetValue("ValueNames", result); return result;} 00346 00347 //! \brief Get a named value with type int 00348 //! \param name the name of the value to retrieve 00349 //! \param value the value retrieved upon success 00350 //! \returns true if an int value was retrieved, false otherwise 00351 //! \details GetIntValue() is used to ensure we don't accidentally try to get an 00352 //! unsigned int or some other type when we mean int (which is the most common case) 00353 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00354 //! GetRequiredParameter() and GetRequiredIntParameter() 00355 CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const 00356 {return GetValue(name, value);} 00357 00358 //! \brief Get a named value with type int, with default 00359 //! \param name the name of the value to retrieve 00360 //! \param defaultValue the default value if the name does not exist 00361 //! \returns the value retrieved on success or the default value 00362 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00363 //! GetRequiredParameter() and GetRequiredIntParameter() 00364 CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const 00365 {return GetValueWithDefault(name, defaultValue);} 00366 00367 //! \brief Ensures an expected name and type is present 00368 //! \param name the name of the value 00369 //! \param stored the type that was stored for the name 00370 //! \param retrieving the type that is being retrieved for the name 00371 //! \throws ValueTypeMismatch 00372 //! \details ThrowIfTypeMismatch() effectively performs a type safety check. 00373 //! stored and retrieving are C++ mangled names for the type. 00374 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00375 //! GetRequiredParameter() and GetRequiredIntParameter() 00376 CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving) 00377 {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);} 00378 00379 //! \brief Retrieves a required name/value pair 00380 //! \tparam T class or type 00381 //! \param className the name of the class 00382 //! \param name the name of the value 00383 //! \param value reference to a variable to receive the value 00384 //! \throws InvalidArgument 00385 //! \details GetRequiredParameter() throws InvalidArgument if the name 00386 //! is not present or not of the expected type T. 00387 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00388 //! GetRequiredParameter() and GetRequiredIntParameter() 00389 template <class T> 00390 void GetRequiredParameter(const char *className, const char *name, T &value) const 00391 { 00392 if (!GetValue(name, value)) 00393 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); 00394 } 00395 00396 //! \brief Retrieves a required name/value pair 00397 //! \param className the name of the class 00398 //! \param name the name of the value 00399 //! \param value reference to a variable to receive the value 00400 //! \throws InvalidArgument 00401 //! \details GetRequiredParameter() throws InvalidArgument if the name 00402 //! is not present or not of the expected type T. 00403 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00404 //! GetRequiredParameter() and GetRequiredIntParameter() 00405 CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const 00406 { 00407 if (!GetIntValue(name, value)) 00408 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); 00409 } 00410 00411 //! \brief Get a named value 00412 //! \param name the name of the object or value to retrieve 00413 //! \param valueType reference to a variable that receives the value 00414 //! \param pValue void pointer to a variable that receives the value 00415 //! \returns true if the value was retrieved, false otherwise 00416 //! \details GetVoidValue() retrives the value of name if it exists. 00417 //! \note GetVoidValue() is an internal function and should be implemented 00418 //! by derived classes. Users should use one of the other functions instead. 00419 //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 00420 //! GetRequiredParameter() and GetRequiredIntParameter() 00421 CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0; 00422 }; 00423 00424 #if CRYPTOPP_DOXYGEN_PROCESSING 00425 00426 //! \brief Namespace containing value name definitions. 00427 //! \details Name is part of the CryptoPP namespace. 00428 //! \details The semantics of value names, types are: 00429 //! <pre> 00430 //! ThisObject:ClassName (ClassName, copy of this object or a subobject) 00431 //! ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject) 00432 //! </pre> 00433 DOCUMENTED_NAMESPACE_BEGIN(Name) 00434 // more names defined in argnames.h 00435 DOCUMENTED_NAMESPACE_END 00436 00437 //! \brief Namespace containing weak and wounded algorithms. 00438 //! \details Weak is part of the CryptoPP namespace. Schemes and algorithms are moved into Weak 00439 //! when their security level is reduced to an unacceptable value by contemporary standards. 00440 DOCUMENTED_NAMESPACE_BEGIN(Weak) 00441 // weak and wounded algorithms 00442 DOCUMENTED_NAMESPACE_END 00443 #endif 00444 00445 //! \brief An empty set of name-value pairs 00446 extern CRYPTOPP_DLL const NameValuePairs &g_nullNameValuePairs; 00447 00448 // ******************************************************** 00449 00450 //! \class Clonable 00451 //! \brief Interface for cloning objects 00452 //! \note this is \a not implemented by most classes 00453 //! \sa ClonableImpl, NotCopyable 00454 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable 00455 { 00456 public: 00457 virtual ~Clonable() {} 00458 00459 //! \brief Copies this object 00460 //! \returns a copy of this object 00461 //! \throws NotImplemented 00462 //! \note this is \a not implemented by most classes 00463 //! \sa NotCopyable 00464 virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0 00465 }; 00466 00467 //! \class Algorithm 00468 //! \brief Interface for all crypto algorithms 00469 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable 00470 { 00471 public: 00472 //! \brief Interface for all crypto algorithms 00473 //! \param checkSelfTestStatus determines whether the object can proceed if the self 00474 //! tests have not been run or failed. 00475 //! \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true, 00476 //! this constructor throws SelfTestFailure if the self test hasn't been run or fails. 00477 //! \details FIPS 140-2 compliance is disabled by default. It is only used by certain 00478 //! versions of the library when the library is built as a DLL on Windows. Also see 00479 //! CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h. 00480 Algorithm(bool checkSelfTestStatus = true); 00481 00482 //! \brief Provides the name of this algorithm 00483 //! \returns the standard algorithm name 00484 //! \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms 00485 //! do not have standard names yet. For example, there is no standard algorithm name for 00486 //! Shoup's ECIES. 00487 //! \note AlgorithmName is not universally implemented yet 00488 virtual std::string AlgorithmName() const {return "unknown";} 00489 00490 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 00491 virtual ~Algorithm() {} 00492 #endif 00493 }; 00494 00495 //! \class SimpleKeyingInterface 00496 //! Interface for algorithms that take byte strings as keys 00497 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface 00498 { 00499 public: 00500 virtual ~SimpleKeyingInterface() {} 00501 00502 //! \brief Returns smallest valid key length in bytes 00503 virtual size_t MinKeyLength() const =0; 00504 //! \brief Returns largest valid key length in bytes 00505 virtual size_t MaxKeyLength() const =0; 00506 //! \brief Returns default (recommended) key length in bytes 00507 virtual size_t DefaultKeyLength() const =0; 00508 00509 //! \brief 00510 //! \returns the smallest valid key length in bytes that is greater than or equal to <tt>min(n, GetMaxKeyLength())</tt> 00511 virtual size_t GetValidKeyLength(size_t n) const =0; 00512 00513 //! \brief Returns whether keylength is a valid key length 00514 //! \details Internally the function calls GetValidKeyLength() 00515 virtual bool IsValidKeyLength(size_t keylength) const 00516 {return keylength == GetValidKeyLength(keylength);} 00517 00518 //! \brief Sets or reset the key of this object 00519 //! \param key the key to use when keying the object 00520 //! \param length the size of the key, in bytes 00521 //! \param params additional initialization parameters that cannot be passed 00522 //! directly through the constructor 00523 virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms = g_nullNameValuePairs); 00524 00525 //! \brief Sets or reset the key of this object 00526 //! \param key the key to use when keying the object 00527 //! \param length the size of the key, in bytes 00528 //! \param rounds the number of rounds to apply the transformation function, 00529 //! if applicable 00530 //! \details SetKeyWithRounds calls SetKey with an NameValuePairs 00531 //! object that just specifies rounds. rounds is an integer parameter, 00532 //! and <tt>-1</tt> means use the default number of rounds. 00533 void SetKeyWithRounds(const byte *key, size_t length, int rounds); 00534 00535 //! \brief Sets or reset the key of this object 00536 //! \param key the key to use when keying the object 00537 //! \param length the size of the key, in bytes 00538 //! \param iv the intiialization vector to use when keying the object 00539 //! \param ivLength the size of the iv, in bytes 00540 //! \details SetKeyWithIV calls SetKey with an NameValuePairs object 00541 //! that just specifies iv. iv is a byte buffer with size ivLength. 00542 void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength); 00543 00544 //! \brief Sets or reset the key of this object 00545 //! \param key the key to use when keying the object 00546 //! \param length the size of the key, in bytes 00547 //! \param iv the intiialization vector to use when keying the object 00548 //! \details SetKeyWithIV calls SetKey with an NameValuePairs object 00549 //! that just specifies iv. iv is a byte buffer, and it must have 00550 //! a size IVSize. 00551 void SetKeyWithIV(const byte *key, size_t length, const byte *iv) 00552 {SetKeyWithIV(key, length, iv, IVSize());} 00553 00554 //! \brief Provides IV requirements as an enumerated value. 00555 enum IV_Requirement { 00556 //! \brief The IV must be unique 00557 UNIQUE_IV = 0, 00558 //! \brief The IV must be random 00559 RANDOM_IV, 00560 //! \brief The IV must be unpredictable 00561 UNPREDICTABLE_RANDOM_IV, 00562 //! \brief The IV is set by the object 00563 INTERNALLY_GENERATED_IV, 00564 //! \brief The object does not use an IV 00565 NOT_RESYNCHRONIZABLE 00566 }; 00567 00568 //! returns the minimal requirement for secure IVs 00569 virtual IV_Requirement IVRequirement() const =0; 00570 00571 //! returns whether the object can be resynchronized (i.e. supports initialization vectors) 00572 /*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */ 00573 bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;} 00574 //! returns whether the object can use random IVs (in addition to ones returned by GetNextIV) 00575 bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;} 00576 //! returns whether the object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV) 00577 bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;} 00578 //! returns whether the object can use structured IVs, for example a counter (in addition to ones returned by GetNextIV) 00579 bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;} 00580 00581 //! \brief Returns length of the IV accepted by this object 00582 //! \details The default implementation throws NotImplemented 00583 virtual unsigned int IVSize() const 00584 {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");} 00585 //! returns default length of IVs accepted by this object 00586 unsigned int DefaultIVLength() const {return IVSize();} 00587 //! returns minimal length of IVs accepted by this object 00588 virtual unsigned int MinIVLength() const {return IVSize();} 00589 //! returns maximal length of IVs accepted by this object 00590 virtual unsigned int MaxIVLength() const {return IVSize();} 00591 //! resynchronize with an IV. ivLength=-1 means use IVSize() 00592 virtual void Resynchronize(const byte *iv, int ivLength=-1) { 00593 CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength); 00594 throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization"); 00595 } 00596 00597 //! \brief Gets a secure IV for the next message 00598 //! \param rng a RandomNumberGenerator to produce keying material 00599 //! \param iv a block of bytes to receive the IV 00600 //! \details This method should be called after you finish encrypting one message and are ready 00601 //! to start the next one. After calling it, you must call SetKey() or Resynchronize() 00602 //! before using this object again. 00603 //! \details key must be at least IVSize() in length. 00604 //! \note This method is not implemented on decryption objects. 00605 virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv); 00606 00607 protected: 00608 //! \brief Returns the base class Algorithm 00609 //! \returns the base class Algorithm 00610 virtual const Algorithm & GetAlgorithm() const =0; 00611 00612 //! \brief Sets the key for this object without performing parameter validation 00613 //! \param key a byte buffer used to key the cipher 00614 //! \param length the length of the byte buffer 00615 //! \param params additional parameters passed as NameValuePairs 00616 //! \details key must be at least DEFAULT_KEYLENGTH in length. 00617 virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms) =0; 00618 00619 //! \brief Validates the key length 00620 //! \param length the size of the keying material, in bytes 00621 //! \throws InvalidKeyLength if the key length is invalid 00622 void ThrowIfInvalidKeyLength(size_t length); 00623 00624 //! \brief Validates the object 00625 //! \throws InvalidArgument if the IV is present 00626 //! \details Internally, the default implementation calls IsResynchronizable() and throws 00627 //! InvalidArgument if the function returns true. 00628 //! \note called when no IV is passed 00629 void ThrowIfResynchronizable(); 00630 00631 //! \brief Validates the IV 00632 //! \param iv the IV with a length of IVSize, in bytes 00633 //! \throws InvalidArgument on failure 00634 //! \details Internally, the default implementation checks the iv. If iv is not NULL, 00635 //! then the function succeeds. If iv is NULL, then IVRequirement is checked against 00636 //! UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then 00637 //! then the function succeeds. Otherwise, an exception is thrown. 00638 void ThrowIfInvalidIV(const byte *iv); 00639 00640 //! \brief Validates the IV length 00641 //! \param length the size of the IV, in bytes 00642 //! \throws InvalidArgument if the number of rounds are invalid 00643 size_t ThrowIfInvalidIVLength(int length); 00644 00645 //! \brief retrieves and validates the IV 00646 //! \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter 00647 //! \param size the length of the IV, in bytes 00648 //! \returns a pointer to the first byte of the IV 00649 //! \throws InvalidArgument if the number of rounds are invalid 00650 const byte * GetIVAndThrowIfInvalid(const NameValuePairs ¶ms, size_t &size); 00651 00652 //! \brief Validates the key length 00653 //! \param length the size of the keying material, in bytes 00654 inline void AssertValidKeyLength(size_t length) const 00655 {CRYPTOPP_UNUSED(length); assert(IsValidKeyLength(length));} 00656 }; 00657 00658 //! \brief Interface for the data processing part of block ciphers 00659 //! \details Classes derived from BlockTransformation are block ciphers 00660 //! in ECB mode (for example the DES::Encryption class), which are stateless. 00661 //! These classes should not be used directly, but only in combination with 00662 //! a mode class (see CipherModeDocumentation in modes.h). 00663 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm 00664 { 00665 public: 00666 //! \brief Encrypt or decrypt a block 00667 //! \param inBlock the input message before processing 00668 //! \param outBlock the output message after processing 00669 //! \param xorBlock an optional XOR mask 00670 //! \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock. 00671 //! \details The size of the block is determined by the block cipher and its documentation. Use 00672 //! BLOCKSIZE at compile time, or BlockSize() at runtime. 00673 //! \note The message can be transformed in-place, or the buffers must \a not overlap 00674 //! \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize() 00675 virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0; 00676 00677 //! \brief Encrypt or decrypt a block 00678 //! \param inBlock the input message before processing 00679 //! \param outBlock the output message after processing 00680 //! \details ProcessBlock encrypts or decrypts inBlock and write to outBlock. 00681 //! \details The size of the block is determined by the block cipher and its documentation. 00682 //! Use BLOCKSIZE at compile time, or BlockSize() at runtime. 00683 //! \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize() 00684 //! \note The message can be transformed in-place, or the buffers must \a not overlap 00685 void ProcessBlock(const byte *inBlock, byte *outBlock) const 00686 {ProcessAndXorBlock(inBlock, NULL, outBlock);} 00687 00688 //! \brief Encrypt or decrypt a block in place 00689 //! \param inoutBlock the input message before processing 00690 //! \details ProcessBlock encrypts or decrypts inoutBlock in-place. 00691 //! \details The size of the block is determined by the block cipher and its documentation. 00692 //! Use BLOCKSIZE at compile time, or BlockSize() at runtime. 00693 //! \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize() 00694 void ProcessBlock(byte *inoutBlock) const 00695 {ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);} 00696 00697 //! Provides the block size of the cipher 00698 //! \returns the block size of the cipher, in bytes 00699 virtual unsigned int BlockSize() const =0; 00700 00701 //! \brief Provides input and output data alignment for optimal performance. 00702 //! \returns the input data alignment that provides optimal performance 00703 virtual unsigned int OptimalDataAlignment() const; 00704 00705 //! returns true if this is a permutation (i.e. there is an inverse transformation) 00706 virtual bool IsPermutation() const {return true;} 00707 00708 //! \brief Determines if the cipher is being operated in its forward direction 00709 //! \returns true if DIR is ENCRYPTION, false otherwise 00710 //! \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection() 00711 virtual bool IsForwardTransformation() const =0; 00712 00713 //! \brief Determines the number of blocks that can be processed in parallel 00714 //! \return the number of blocks that can be processed in parallel, for bit-slicing implementations 00715 //! \details Bit-slicing is often used to improve throughput and minimize timing attacks. 00716 virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;} 00717 00718 //! \brief Bit flags that control AdvancedProcessBlocks() behavior 00719 enum FlagsForAdvancedProcessBlocks { 00720 //! \brief inBlock is a counter 00721 BT_InBlockIsCounter=1, 00722 //! \brief should not modify block pointers 00723 BT_DontIncrementInOutPointers=2, 00724 //! \brief 00725 BT_XorInput=4, 00726 //! \brief perform the transformation in reverse 00727 BT_ReverseDirection=8, 00728 //! \brief 00729 BT_AllowParallel=16}; 00730 00731 //! \brief Encrypt and xor multiple blocks using additional flags 00732 //! \param inBlocks the input message before processing 00733 //! \param xorBlocks an optional XOR mask 00734 //! \param outBlocks the output message after processing 00735 //! \param length the size of the blocks, in bytes 00736 //! \param flags additional flags to control processing 00737 //! \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags. 00738 //! \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified. 00739 virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const; 00740 00741 //! \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection() 00742 inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;} 00743 00744 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 00745 virtual ~BlockTransformation() {} 00746 #endif 00747 }; 00748 00749 //! \class StreamTransformation 00750 //! \brief Interface for the data processing portion of stream ciphers 00751 //! \sa StreamTransformationFilter() 00752 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm 00753 { 00754 public: 00755 //! \brief Provides a reference to this object 00756 //! \returns A reference to this object 00757 //! \details Useful for passing a temporary object to a function that takes a non-const reference 00758 StreamTransformation& Ref() {return *this;} 00759 00760 //! \brief Provides the mandatory block size of the cipher 00761 //! \returns The block size of the cipher if input must be processed in blocks, 1 otherwise 00762 virtual unsigned int MandatoryBlockSize() const {return 1;} 00763 00764 //! \brief Provides the input block size most efficient for this cipher. 00765 //! \returns The input block size that is most efficient for the cipher 00766 //! \details The base class implemnetation returns MandatoryBlockSize(). 00767 //! \note Optimal input length is 00768 //! <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>. 00769 virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();} 00770 00771 //! \brief Provides the number of bytes used in the current block when processing at optimal block size. 00772 //! \returns the number of bytes used in the current block when processing at the optimal block size 00773 virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;} 00774 00775 //! \brief Provides input and output data alignment for optimal performance. 00776 //! \returns the input data alignment that provides optimal performance 00777 virtual unsigned int OptimalDataAlignment() const; 00778 00779 //! \brief Encrypt or decrypt an array of bytes 00780 //! \param outString the output byte buffer 00781 //! \param inString the input byte buffer 00782 //! \param length the size of the input and output byte buffers, in bytes 00783 //! \details Either <tt>inString == outString</tt>, or they must not overlap. 00784 virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0; 00785 00786 //! \brief Encrypt or decrypt the last block of data 00787 //! \param outString the output byte buffer 00788 //! \param inString the input byte buffer 00789 //! \param length the size of the input and output byte buffers, in bytes 00790 //! ProcessLastBlock is used when the last block of data is special. 00791 //! Currently the only use of this function is CBC-CTS mode. 00792 virtual void ProcessLastBlock(byte *outString, const byte *inString, size_t length); 00793 00794 //! returns the minimum size of the last block, 0 indicating the last block is not special 00795 virtual unsigned int MinLastBlockSize() const {return 0;} 00796 00797 //! \brief Encrypt or decrypt a string of bytes 00798 //! \param inoutString the string to process 00799 //! \param length the size of the inoutString, in bytes 00800 //! \details Internally, the base class implementation calls ProcessData(). 00801 inline void ProcessString(byte *inoutString, size_t length) 00802 {ProcessData(inoutString, inoutString, length);} 00803 00804 //! \brief Encrypt or decrypt a string of bytes 00805 //! \param outString the output string to process 00806 //! \param inString the input string to process 00807 //! \param length the size of the input and output strings, in bytes 00808 //! \details Internally, the base class implementation calls ProcessData(). 00809 inline void ProcessString(byte *outString, const byte *inString, size_t length) 00810 {ProcessData(outString, inString, length);} 00811 00812 //! \brief Encrypt or decrypt a byte 00813 //! \param input the input byte to process 00814 //! \details Internally, the base class implementation calls ProcessData() with a size of 1. 00815 inline byte ProcessByte(byte input) 00816 {ProcessData(&input, &input, 1); return input;} 00817 00818 //! \brief Determines whether the cipher supports random access 00819 //! \returns true if the cipher supports random access, false otherwise 00820 virtual bool IsRandomAccess() const =0; 00821 00822 //! \brief Seek to an absolute position 00823 //! \param pos position to seek 00824 //! \throws NotImplemented 00825 //! \details The base class implementation throws NotImplemented. The function 00826 //! asserts IsRandomAccess() in debug builds. 00827 virtual void Seek(lword pos) 00828 { 00829 CRYPTOPP_UNUSED(pos); 00830 assert(!IsRandomAccess()); 00831 throw NotImplemented("StreamTransformation: this object doesn't support random access"); 00832 } 00833 00834 //! \brief Determines whether the cipher is self-inverting 00835 //! \returns true if the cipher is self-inverting, false otherwise 00836 //! \details IsSelfInverting determines whether this transformation is 00837 //! self-inverting (e.g. xor with a keystream). 00838 virtual bool IsSelfInverting() const =0; 00839 00840 //! \brief Determines if the cipher is being operated in its forward direction 00841 //! \returns true if DIR is ENCRYPTION, false otherwise 00842 //! \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection() 00843 virtual bool IsForwardTransformation() const =0; 00844 00845 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 00846 virtual ~StreamTransformation() {} 00847 #endif 00848 }; 00849 00850 //! \class HashTransformation 00851 //! \brief Interface for hash functions and data processing part of MACs 00852 //! \details HashTransformation objects are stateful. They are created in an initial state, 00853 //! change state as Update() is called, and return to the initial 00854 //! state when Final() is called. This interface allows a large message to 00855 //! be hashed in pieces by calling Update() on each piece followed by 00856 //! calling Final(). 00857 //! \sa HashFilter(), HashVerificationFilter() 00858 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm 00859 { 00860 public: 00861 //! \brief Provides a reference to this object 00862 //! \returns A reference to this object 00863 //! \details Useful for passing a temporary object to a function that takes a non-const reference 00864 HashTransformation& Ref() {return *this;} 00865 00866 //! \brief Updates a hash with additional input 00867 //! \param input the additional input as a buffer 00868 //! \param length the size of the buffer, in bytes 00869 virtual void Update(const byte *input, size_t length) =0; 00870 00871 //! \brief Request space which can be written into by the caller 00872 //! \param size the requested size of the buffer 00873 //! \details The purpose of this method is to help avoid extra memory allocations. 00874 //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made, 00875 //! size is the requested size of the buffer. When the call returns, size is the size of 00876 //! the array returned to the caller. 00877 //! \details The base class implementation sets size to 0 and returns NULL. 00878 //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of 00879 virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULL;} 00880 00881 //! \brief Computes the hash of the current message 00882 //! \param digest a pointer to the buffer to receive the hash 00883 //! \details digest must be equal to (or greater than) DigestSize(). Final() restarts the 00884 //! hash for a new message. 00885 virtual void Final(byte *digest) 00886 {TruncatedFinal(digest, DigestSize());} 00887 00888 //! \brief Restart the hash 00889 //! \details Discards the current state, and restart for a new message 00890 virtual void Restart() 00891 {TruncatedFinal(NULL, 0);} 00892 00893 //! Provides the digest size of the hash 00894 //! \returns the digest size of the hash. 00895 //! \details Calls to Final() require a buffer that is equal to (or greater than) DigestSize(). 00896 virtual unsigned int DigestSize() const =0; 00897 00898 //! Provides the tag size of the hash 00899 //! \returns the tag size of the hash. 00900 //! \details Same as DigestSize(). 00901 unsigned int TagSize() const {return DigestSize();} 00902 00903 //! \brief Provides the block size of the compression function 00904 //! \returns the block size of the compression function, in bytes 00905 //! \details BlockSize() will return 0 if the hash is not block based. For example, 00906 //! SHA3 is a recursive hash (not an iterative hash), and it does not have a block size. 00907 virtual unsigned int BlockSize() const {return 0;} 00908 00909 //! \brief Provides the input block size most efficient for this hash. 00910 //! \returns The input block size that is most efficient for the cipher 00911 //! \details The base class implemnetation returns MandatoryBlockSize(). 00912 //! \note Optimal input length is 00913 //! <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>. 00914 virtual unsigned int OptimalBlockSize() const {return 1;} 00915 00916 //! \brief Provides input and output data alignment for optimal performance 00917 //! \returns the input data alignment that provides optimal performance 00918 virtual unsigned int OptimalDataAlignment() const; 00919 00920 //! \brief Updates the hash with additional input and computes the hash of the current message 00921 //! \param digest a pointer to the buffer to receive the hash 00922 //! \param input the additional input as a buffer 00923 //! \param length the size of the buffer, in bytes 00924 //! \details Use this if your input is in one piece and you don't want to call Update() 00925 //! and Final() separately 00926 //! \details CalculateDigest() restarts the hash for the next nmessage. 00927 virtual void CalculateDigest(byte *digest, const byte *input, size_t length) 00928 {Update(input, length); Final(digest);} 00929 00930 //! \brief Verifies the hash of the current message 00931 //! \param digest a pointer to the buffer of an \a existing hash 00932 //! \returns \p true if the existing hash matches the computed hash, \p false otherwise 00933 //! \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize() 00934 //! \details Calls to Verify() require a buffer that is equal to (or greater than) DigestSize(). 00935 //! \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is 00936 //! a constant time comparison function. digestLength cannot exceed DigestSize(). 00937 //! \details Verify() restarts the hash for the next nmessage. 00938 virtual bool Verify(const byte *digest) 00939 {return TruncatedVerify(digest, DigestSize());} 00940 00941 //! \brief Updates the hash with additional input and verifies the hash of the current message 00942 //! \param digest a pointer to the buffer of an \a existing hash 00943 //! \param input the additional input as a buffer 00944 //! \param length the size of the buffer, in bytes 00945 //! \returns \p true if the existing hash matches the computed hash, \p false otherwise 00946 //! \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize() 00947 //! \details Use this if your input is in one piece and you don't want to call Update() 00948 //! and Verify() separately 00949 //! \details VerifyDigest() performs a bitwise compare on the buffers using VerifyBufsEqual(), 00950 //! which is a constant time comparison function. digestLength cannot exceed DigestSize(). 00951 //! \details VerifyDigest() restarts the hash for the next nmessage. 00952 virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length) 00953 {Update(input, length); return Verify(digest);} 00954 00955 //! \brief Computes the hash of the current message 00956 //! \param digest a pointer to the buffer to receive the hash 00957 //! \param digestSize the size of the truncated digest, in bytes 00958 //! \details TruncatedFinal() call Final() and then copies digestSize bytes to digest 00959 //! \details TruncatedFinal() restarts the hash for the next nmessage. 00960 virtual void TruncatedFinal(byte *digest, size_t digestSize) =0; 00961 00962 //! \brief Updates the hash with additional input and computes the hash of the current message 00963 //! \param digest a pointer to the buffer to receive the hash 00964 //! \param digestSize the length of the truncated hash, in bytes 00965 //! \param input the additional input as a buffer 00966 //! \param length the size of the buffer, in bytes 00967 //! \details Use this if your input is in one piece and you don't want to call Update() 00968 //! and CalculateDigest() separately. 00969 //! \details CalculateTruncatedDigest() restarts the hash for the next nmessage. 00970 virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length) 00971 {Update(input, length); TruncatedFinal(digest, digestSize);} 00972 00973 //! \brief Verifies the hash of the current message 00974 //! \param digest a pointer to the buffer of an \a existing hash 00975 //! \param digestLength the size of the truncated hash, in bytes 00976 //! \returns \p true if the existing hash matches the computed hash, \p false otherwise 00977 //! \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize() 00978 //! \details TruncatedVerify() is a truncated version of Verify(). It can operate on a 00979 //! buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize(). 00980 //! \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is 00981 //! a constant time comparison function. digestLength cannot exceed DigestSize(). 00982 //! \details TruncatedVerify() restarts the hash for the next nmessage. 00983 virtual bool TruncatedVerify(const byte *digest, size_t digestLength); 00984 00985 //! \brief Updates the hash with additional input and verifies the hash of the current message 00986 //! \param digest a pointer to the buffer of an \a existing hash 00987 //! \param digestLength the size of the truncated hash, in bytes 00988 //! \param input the additional input as a buffer 00989 //! \param length the size of the buffer, in bytes 00990 //! \returns \p true if the existing hash matches the computed hash, \p false otherwise 00991 //! \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize() 00992 //! \details Use this if your input is in one piece and you don't want to call Update() 00993 //! and TruncatedVerify() separately. 00994 //! \details VerifyTruncatedDigest() is a truncated version of VerifyDigest(). It can operate 00995 //! on a buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize(). 00996 //! \details VerifyTruncatedDigest() restarts the hash for the next nmessage. 00997 virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length) 00998 {Update(input, length); return TruncatedVerify(digest, digestLength);} 00999 01000 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 01001 virtual ~HashTransformation() {} 01002 #endif 01003 01004 protected: 01005 //! \brief Exception thrown when the truncated digest size is greater than DigestSize() 01006 void ThrowIfInvalidTruncatedSize(size_t size) const; 01007 }; 01008 01009 typedef HashTransformation HashFunction; 01010 01011 //! \brief Interface for one direction (encryption or decryption) of a block cipher 01012 /*! \note These objects usually should not be used directly. See BlockTransformation for more details. */ 01013 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation 01014 { 01015 protected: 01016 const Algorithm & GetAlgorithm() const {return *this;} 01017 }; 01018 01019 //! \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode 01020 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation 01021 { 01022 protected: 01023 const Algorithm & GetAlgorithm() const {return *this;} 01024 }; 01025 01026 //! \brief Interface for message authentication codes 01027 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation 01028 { 01029 protected: 01030 const Algorithm & GetAlgorithm() const {return *this;} 01031 }; 01032 01033 //! \brief Interface for one direction (encryption or decryption) of a stream cipher or block cipher mode with authentication 01034 /*! The StreamTransformation part of this interface is used to encrypt/decrypt the data, and the MessageAuthenticationCode part of this 01035 interface is used to input additional authenticated data (AAD, which is MAC'ed but not encrypted), and to generate/verify the MAC. */ 01036 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation 01037 { 01038 public: 01039 //! 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 01040 class BadState : public Exception 01041 { 01042 public: 01043 explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {} 01044 explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {} 01045 }; 01046 01047 //! the maximum length of AAD that can be input before the encrypted data 01048 virtual lword MaxHeaderLength() const =0; 01049 //! the maximum length of encrypted data 01050 virtual lword MaxMessageLength() const =0; 01051 //! the maximum length of AAD that can be input after the encrypted data 01052 virtual lword MaxFooterLength() const {return 0;} 01053 //! if this function returns true, SpecifyDataLengths() must be called before attempting to input data 01054 /*! This is the case for some schemes, such as CCM. */ 01055 virtual bool NeedsPrespecifiedDataLengths() const {return false;} 01056 //! this function only needs to be called if NeedsPrespecifiedDataLengths() returns true 01057 void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0); 01058 //! encrypt and generate MAC in one call. will truncate MAC if macSize < TagSize() 01059 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); 01060 //! decrypt and verify MAC in one call, returning true iff MAC is valid. will assume MAC is truncated if macLength < TagSize() 01061 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); 01062 01063 // redeclare this to avoid compiler ambiguity errors 01064 virtual std::string AlgorithmName() const =0; 01065 01066 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 01067 virtual ~AuthenticatedSymmetricCipher() {} 01068 #endif 01069 01070 protected: 01071 const Algorithm & GetAlgorithm() const 01072 {return *static_cast<const MessageAuthenticationCode *>(this);} 01073 virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength) 01074 {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);} 01075 }; 01076 01077 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01078 typedef SymmetricCipher StreamCipher; 01079 #endif 01080 01081 //! \class RandomNumberGenerator 01082 //! \brief Interface for random number generators 01083 //! \details The library provides a number of random number generators, from software based to hardware based generators. 01084 //! \details All generated values are uniformly distributed over the range specified. 01085 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm 01086 { 01087 public: 01088 //! \brief Update RNG state with additional unpredictable values 01089 //! \param input the entropy to add to the generator 01090 //! \param length the size of the input buffer 01091 //! \throws NotImplemented 01092 //! \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy() to test for the 01093 //! ability to use additional entropy. 01094 //! \details If a derived class does not override IncorporateEntropy(), then the base class throws 01095 //! NotImplemented. 01096 virtual void IncorporateEntropy(const byte *input, size_t length) 01097 { 01098 CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length); 01099 throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented"); 01100 } 01101 01102 //! \brief Determines if a generator can accept additional entropy 01103 //! \returns true if IncorporateEntropy() is implemented 01104 virtual bool CanIncorporateEntropy() const {return false;} 01105 01106 //! \brief Generate new random byte and return it 01107 //! \returns a random 8-bit byte 01108 //! \details Default implementation calls GenerateBlock() with one byte. 01109 //! \details All generated values are uniformly distributed over the range specified within the 01110 //! the contraints of a particular generator. 01111 virtual byte GenerateByte(); 01112 01113 //! \brief Generate new random bit and return it 01114 //! \returns a random bit 01115 //! \details The default implementation calls GenerateByte() and return its lowest bit. 01116 //! \details All generated values are uniformly distributed over the range specified within the 01117 //! the contraints of a particular generator. 01118 virtual unsigned int GenerateBit(); 01119 01120 //! \brief Generate a random 32 bit word in the range min to max, inclusive 01121 //! \param min the lower bound of the range 01122 //! \param max the upper bound of the range 01123 //! \returns a random 32-bit word 01124 //! \details The default implementation calls Crop() on the difference between max and 01125 //! min, and then returns the result added to min. 01126 //! \details All generated values are uniformly distributed over the range specified within the 01127 //! the contraints of a particular generator. 01128 virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL); 01129 01130 //! \brief Generate random array of bytes 01131 //! \param output the byte buffer 01132 //! \param size the length of the buffer, in bytes 01133 //! \details All generated values are uniformly distributed over the range specified within the 01134 //! the contraints of a particular generator. 01135 //! \note A derived generator \a must override either GenerateBlock() or 01136 //! GenerateIntoBufferedTransformation(). They can override both, or have one call the other. 01137 virtual void GenerateBlock(byte *output, size_t size); 01138 01139 //! \brief Generate random bytes into a BufferedTransformation 01140 //! \param target the BufferedTransformation object which receives the bytes 01141 //! \param channel the channel on which the bytes should be pumped 01142 //! \param length the number of bytes to generate 01143 //! \details The default implementation calls GenerateBlock() and pumps the result into 01144 //! the DEFAULT_CHANNEL of the target. 01145 //! \details All generated values are uniformly distributed over the range specified within the 01146 //! the contraints of a particular generator. 01147 //! \note A derived generator \a must override either GenerateBlock() or 01148 //! GenerateIntoBufferedTransformation(). They can override both, or have one call the other. 01149 virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length); 01150 01151 //! \brief Generate and discard n bytes 01152 //! \param n the number of bytes to generate and discard 01153 virtual void DiscardBytes(size_t n); 01154 01155 //! \brief Randomly shuffle the specified array 01156 //! \param begin an iterator to the first element in the array 01157 //! \param end an iterator beyond the last element in the array 01158 //! \details The resulting permutation is uniformly distributed. 01159 template <class IT> void Shuffle(IT begin, IT end) 01160 { 01161 // TODO: What happens if there are more than 2^32 elements? 01162 for (; begin != end; ++begin) 01163 std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1)); 01164 } 01165 01166 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 01167 virtual ~RandomNumberGenerator() {} 01168 #endif 01169 01170 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01171 byte GetByte() {return GenerateByte();} 01172 unsigned int GetBit() {return GenerateBit();} 01173 word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);} 01174 word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);} 01175 void GetBlock(byte *output, size_t size) {GenerateBlock(output, size);} 01176 #endif 01177 01178 }; 01179 01180 //! \brief Random Number Generator that does not produce random numbers 01181 //! \returns reference that can be passed to functions that require a RandomNumberGenerator 01182 //! \details NullRNG() returns a reference that can be passed to functions that require a 01183 //! RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented 01184 //! when a generation function is called. 01185 //! \sa ClassNullRNG 01186 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG(); 01187 01188 //! \class WaitObjectContainer 01189 class WaitObjectContainer; 01190 //! \class CallStack 01191 class CallStack; 01192 01193 //! \brief Interface for objects that can be waited on. 01194 class CRYPTOPP_NO_VTABLE Waitable 01195 { 01196 public: 01197 virtual ~Waitable() {} 01198 01199 //! \brief Maximum number of wait objects that this object can return 01200 virtual unsigned int GetMaxWaitObjectCount() const =0; 01201 01202 //! \brief Retrieves waitable objects 01203 //! \param container the wait container to receive the references to the objects. 01204 //! \param callStack CallStack object used to select waitable objects 01205 //! \details GetWaitObjects is usually called in one of two ways. First, it can 01206 //! be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>. 01207 //! Second, if in an outer GetWaitObjects() method that itself takes a callStack 01208 //! parameter, it can be called like 01209 //! <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>. 01210 virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0; 01211 01212 //! wait on this object 01213 /*! same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container */ 01214 bool Wait(unsigned long milliseconds, CallStack const& callStack); 01215 }; 01216 01217 //! \brief Default channel for BufferedTransformation 01218 //! \details DEFAULT_CHANNEL is equal to an empty string 01219 extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL; 01220 01221 //! \brief Channel for additional authenticated data 01222 //! \details AAD_CHANNEL is equal to "AAD" 01223 extern CRYPTOPP_DLL const std::string AAD_CHANNEL; 01224 01225 //! \brief Interface for buffered transformations 01226 //! \details BufferedTransformation is a generalization of BlockTransformation, 01227 //! StreamTransformation and HashTransformation. 01228 //! \details A buffered transformation is an object that takes a stream of bytes as input (this may 01229 //! be done in stages), does some computation on them, and then places the result into an internal 01230 //! buffer for later retrieval. Any partial result already in the output buffer is not modified 01231 //! by further input. 01232 //! \details If a method takes a "blocking" parameter, and you pass false for it, then the method 01233 //! will return before all input has been processed if the input cannot be processed without waiting 01234 //! (for network buffers to become available, for example). In this case the method will return true 01235 //! or a non-zero integer value. When this happens you must continue to call the method with the same 01236 //! parameters until it returns false or zero, before calling any other method on it or attached 01237 //! /p BufferedTransformation. The integer return value in this case is approximately 01238 //! the number of bytes left to be processed, and can be used to implement a progress bar. 01239 //! \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on 01240 //! the signal to attached BufferedTransformation objects, with propagation decremented at each 01241 //! step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation. 01242 //! \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual 01243 //! number of bytes retrieved, which is the lesser of the request number and MaxRetrievable(). 01244 //! \details \a Most of the input functions, like Put() and PutWord32(), return the number of 01245 //! bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value 01246 //! means bytes remain to be processed. 01247 //! \nosubgrouping 01248 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable 01249 { 01250 public: 01251 // placed up here for CW8 01252 static const std::string &NULL_CHANNEL; // same as DEFAULT_CHANNEL, for backwards compatibility 01253 01254 BufferedTransformation() : Algorithm(false) {} 01255 01256 //! \brief Provides a reference to this object 01257 //! \returns A reference to this object 01258 //! \details Useful for passing a temporary object to a function that takes a non-const reference 01259 BufferedTransformation& Ref() {return *this;} 01260 01261 //! \name INPUT 01262 //@{ 01263 01264 //! \brief Input a byte for processing 01265 //! \param inByte the 8-bit byte (octet) to be processed. 01266 //! \param blocking specifies whether the object should block when processing input. 01267 //! \returns the number of bytes that remain in the block (i.e., bytes not processed) 01268 //! \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>. 01269 size_t Put(byte inByte, bool blocking=true) 01270 {return Put(&inByte, 1, blocking);} 01271 01272 //! \brief Input a byte buffer for processing 01273 //! \param inString the byte buffer to process 01274 //! \param length the size of the string, in bytes 01275 //! \param blocking specifies whether the object should block when processing input 01276 //! \returns the number of bytes that remain in the block (i.e., bytes not processed) 01277 //! \details Internally, Put() calls Put2(). 01278 size_t Put(const byte *inString, size_t length, bool blocking=true) 01279 {return Put2(inString, length, 0, blocking);} 01280 01281 //! Input a 16-bit word for processing. 01282 //! \param value the 16-bit value to be processed 01283 //! \param order the ByteOrder in which the word should be processed 01284 //! \param blocking specifies whether the object should block when processing input 01285 //! \returns the number of bytes that remain in the block (i.e., bytes not processed) 01286 size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 01287 01288 //! Input a 32-bit word for processing. 01289 //! \param value the 32-bit value to be processed. 01290 //! \param order the ByteOrder in which the word should be processed. 01291 //! \param blocking specifies whether the object should block when processing input. 01292 //! \returns the number of bytes that remain in the block (i.e., bytes not processed) 01293 size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 01294 01295 //! \brief Request space which can be written into by the caller 01296 //! \param size the requested size of the buffer 01297 //! \details The purpose of this method is to help avoid extra memory allocations. 01298 //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made, 01299 //! size is the requested size of the buffer. When the call returns, size is the size of 01300 //! the array returned to the caller. 01301 //! \details The base class implementation sets size to 0 and returns NULL. 01302 //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of 01303 //! an ArraySink, the pointer to the array is returned and the size is remaining size. 01304 virtual byte * CreatePutSpace(size_t &size) 01305 {size=0; return NULL;} 01306 01307 //! \brief Determines whether input can be modifed by the callee 01308 //! \returns true if input can be modified, false otherwise 01309 //! \details The base class implementation returns false. 01310 virtual bool CanModifyInput() const 01311 {return false;} 01312 01313 //! \brief Input multiple bytes that may be modified by callee. 01314 //! \param inString the byte buffer to process 01315 //! \param length the size of the string, in bytes 01316 //! \param blocking specifies whether the object should block when processing input 01317 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01318 //! number of bytes that were \a not processed 01319 size_t PutModifiable(byte *inString, size_t length, bool blocking=true) 01320 {return PutModifiable2(inString, length, 0, blocking);} 01321 01322 //! \brief Signals the end of messages to the object 01323 //! \param propagation the number of attached transformations the MessageEnd() signal should be passed 01324 //! \param blocking specifies whether the object should block when processing input 01325 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01326 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01327 bool MessageEnd(int propagation=-1, bool blocking=true) 01328 {return !!Put2(NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);} 01329 01330 //! \brief Input multiple bytes for processing and signal the end of a message 01331 //! \param inString the byte buffer to process 01332 //! \param length the size of the string, in bytes 01333 //! \param propagation the number of attached transformations the MessageEnd() signal should be passed 01334 //! \param blocking specifies whether the object should block when processing input 01335 //! \details Internally, PutMessageEnd() calls Put2() with a modified propagation to 01336 //! ensure all attached transformations finish processing the message. 01337 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01338 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01339 size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true) 01340 {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);} 01341 01342 //! \brief Input multiple bytes for processing 01343 //! \param inString the byte buffer to process 01344 //! \param length the size of the string, in bytes 01345 //! \param messageEnd means how many filters to signal MessageEnd() to, including this one 01346 //! \param blocking specifies whether the object should block when processing input 01347 //! \details Derived classes must implement Put2(). 01348 virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0; 01349 01350 //! \brief Input multiple bytes that may be modified by callee. 01351 //! \param inString the byte buffer to process. 01352 //! \param length the size of the string, in bytes. 01353 //! \param messageEnd means how many filters to signal MessageEnd() to, including this one. 01354 //! \param blocking specifies whether the object should block when processing input. 01355 //! \details Internally, PutModifiable2() calls Put2(). 01356 virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking) 01357 {return Put2(inString, length, messageEnd, blocking);} 01358 01359 //! \brief thrown by objects that have not implemented nonblocking input processing 01360 struct BlockingInputOnly : public NotImplemented 01361 {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}}; 01362 //@} 01363 01364 //! \name WAITING 01365 //@{ 01366 //! \brief Retrieves the maximum number of waitable objects 01367 unsigned int GetMaxWaitObjectCount() const; 01368 01369 //! \brief Retrieves waitable objects 01370 //! \param container the wait container to receive the references to the objects 01371 //! \param callStack CallStack object used to select waitable objects 01372 //! \details GetWaitObjects is usually called in one of two ways. First, it can 01373 //! be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>. 01374 //! Second, if in an outer GetWaitObjects() method that itself takes a callStack 01375 //! parameter, it can be called like 01376 //! <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>. 01377 void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack); 01378 //@} // WAITING 01379 01380 //! \name SIGNALS 01381 //@{ 01382 01383 //! \brief Initialize or reinitialize this object, without signal propagation 01384 //! \param parameters a set of NameValuePairs used to initialize this object 01385 //! \throws NotImplemented 01386 //! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable 01387 //! number of arbitrarily typed arguments. The function avoids the need for multiple constuctors providing 01388 //! all possible combintations of configurable parameters. 01389 //! \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization 01390 //! should be propagated, then use the Initialize() function. 01391 //! \details Setting propagation to <tt>-1</tt> means unlimited propagation. 01392 //! \details If a derived class does not override IsolatedInitialize(), then the base class throws 01393 //! NotImplemented. 01394 virtual void IsolatedInitialize(const NameValuePairs ¶meters) { 01395 CRYPTOPP_UNUSED(parameters); 01396 throw NotImplemented("BufferedTransformation: this object can't be reinitialized"); 01397 } 01398 01399 //! \brief Flushes data buffered by this object, without signal propagation 01400 //! \param hardFlush indicates whether all data should be flushed 01401 //! \param blocking specifies whether the object should block when processing input 01402 //! \note hardFlush must be used with care 01403 virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0; 01404 01405 //! \brief Marks the end of a series of messages, without signal propagation 01406 //! \param blocking specifies whether the object should block when completing the processing on 01407 //! the current series of messages 01408 virtual bool IsolatedMessageSeriesEnd(bool blocking) 01409 {CRYPTOPP_UNUSED(blocking); return false;} 01410 01411 //! \brief Initialize or reinitialize this object, with signal propagation 01412 //! \param parameters a set of NameValuePairs used to initialize or reinitialize this object 01413 //! and attached transformations 01414 //! \param propagation the number of attached transformations the Initialize() signal should be passed 01415 //! \details Initialize() is used to initialize or reinitialize an object using a variable number of 01416 //! arbitrarily typed arguments. The function avoids the need for multiple constuctors providing 01417 //! all possible combintations of configurable parameters. 01418 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01419 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01420 virtual void Initialize(const NameValuePairs ¶meters=g_nullNameValuePairs, int propagation=-1); 01421 01422 //! \brief Flush buffered input and/or output, with signal propagation 01423 //! \param hardFlush is used to indicate whether all data should be flushed 01424 //! \param propagation the number of attached transformations the Flush() signal should be passed 01425 //! \param blocking specifies whether the object should block when processing input 01426 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01427 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01428 //! \note Hard flushes must be used with care. It means try to process and output everything, even if 01429 //! there may not be enough data to complete the action. For example, hard flushing a HexDecoder 01430 //! would cause an error if you do it after inputing an odd number of hex encoded characters. 01431 //! \note For some types of filters, like ZlibDecompressor, hard flushes can only 01432 //! be done at "synchronization points". These synchronization points are positions in the data 01433 //! stream that are created by hard flushes on the corresponding reverse filters, in this 01434 //! example ZlibCompressor. This is useful when zlib compressed data is moved across a 01435 //! network in packets and compression state is preserved across packets, as in the SSH2 protocol. 01436 virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true); 01437 01438 //! \brief Marks the end of a series of messages, with signal propagation 01439 //! \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed 01440 //! \param blocking specifies whether the object should block when processing input 01441 //! \details Each object that receives the signal will perform its processing, decrement 01442 //! propagation, and then pass the signal on to attached transformations if the value is not 0. 01443 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01444 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01445 //! \note There should be a MessageEnd() immediately before MessageSeriesEnd(). 01446 virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true); 01447 01448 //! \brief Set propagation of automatically generated and transferred signals 01449 //! \param propagation then new value 01450 //! \details Setting propagation to <tt>0</tt> means do not automaticly generate signals. Setting 01451 //! propagation to <tt>-1</tt> means unlimited propagation. 01452 virtual void SetAutoSignalPropagation(int propagation) 01453 {CRYPTOPP_UNUSED(propagation);} 01454 01455 //! \brief Retrieve automatic signal propagation value 01456 virtual int GetAutoSignalPropagation() const {return 0;} 01457 public: 01458 01459 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01460 void Close() {MessageEnd();} 01461 #endif 01462 //@} 01463 01464 //! \name RETRIEVAL OF ONE MESSAGE 01465 //@{ 01466 01467 //! \brief Provides the number of bytes ready for retrieval 01468 //! \returns the number of bytes ready for retrieval 01469 //! \details All retrieval functions return the actual number of bytes retrieved, which is 01470 //! the lesser of the request number and MaxRetrievable() 01471 virtual lword MaxRetrievable() const; 01472 01473 //! \brief Determines whether bytes are ready for retrieval 01474 //! \returns true if bytes are available for retrieval, false otherwise 01475 virtual bool AnyRetrievable() const; 01476 01477 //! \brief Retrieve a 8-bit byte 01478 //! \param outByte the 8-bit value to be retrieved 01479 //! \returns the number of bytes consumed during the call. 01480 //! \details Use the return value of Get to detect short reads. 01481 virtual size_t Get(byte &outByte); 01482 01483 //! \brief Retrieve a block of bytes 01484 //! \param outString a block of bytes 01485 //! \param getMax the number of bytes to Get 01486 //! \returns the number of bytes consumed during the call. 01487 //! \details Use the return value of Get to detect short reads. 01488 virtual size_t Get(byte *outString, size_t getMax); 01489 01490 //! \brief Peek a 8-bit byte 01491 //! \param outByte the 8-bit value to be retrieved 01492 //! \returns the number of bytes read during the call. 01493 //! \details Peek does not remove bytes from the object. Use the return value of 01494 //! Get to detect short reads. 01495 virtual size_t Peek(byte &outByte) const; 01496 01497 //! \brief Peek a block of bytes 01498 //! \param outString a block of bytes 01499 //! \param peekMax the number of bytes to Peek 01500 //! \returns the number of bytes read during the call. 01501 //! \details Peek does not remove bytes from the object. Use the return value of 01502 //! Get to detect short reads. 01503 virtual size_t Peek(byte *outString, size_t peekMax) const; 01504 01505 //! \brief Retrieve a 16-bit word 01506 //! \param value the 16-bit value to be retrieved 01507 //! \param order the ByteOrder in which the word should be retrieved 01508 //! \returns the number of bytes consumed during the call. 01509 //! \details Use the return value of GetWord16 to detect short reads. 01510 size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER); 01511 01512 //! \brief Retrieve a 32-bit word 01513 //! \param value the 32-bit value to be retrieved 01514 //! \param order the ByteOrder in which the word should be retrieved 01515 //! \returns the number of bytes consumed during the call. 01516 //! \details Use the return value of GetWord16 to detect short reads. 01517 size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER); 01518 01519 //! \brief Peek a 16-bit word 01520 //! \param value the 16-bit value to be retrieved 01521 //! \param order the ByteOrder in which the word should be retrieved 01522 //! \returns the number of bytes consumed during the call. 01523 //! \details Peek does not consume bytes in the stream. Use the return value 01524 //! of GetWord16 to detect short reads. 01525 size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const; 01526 01527 //! \brief Peek a 32-bit word 01528 //! \param value the 32-bit value to be retrieved 01529 //! \param order the ByteOrder in which the word should be retrieved 01530 //! \returns the number of bytes consumed during the call. 01531 //! \details Peek does not consume bytes in the stream. Use the return value 01532 //! of GetWord16 to detect short reads. 01533 size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const; 01534 01535 //! move transferMax bytes of the buffered output to target as input 01536 01537 //! \brief Transfer bytes from this object to another BufferedTransformation 01538 //! \param target the destination BufferedTransformation 01539 //! \param transferMax the number of bytes to transfer 01540 //! \param channel the channel on which the transfer should occur 01541 //! \returns the number of bytes transferred during the call. 01542 //! \details TransferTo removes bytes from this object and moves them to the destination. 01543 //! \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2. 01544 lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) 01545 {TransferTo2(target, transferMax, channel); return transferMax;} 01546 01547 //! \brief Discard skipMax bytes from the output buffer 01548 //! \param skipMax the number of bytes to discard 01549 //! \details Skip always returns skipMax. 01550 virtual lword Skip(lword skipMax=LWORD_MAX); 01551 01552 //! copy copyMax bytes of the buffered output to target as input 01553 01554 //! \brief Copy bytes from this object to another BufferedTransformation 01555 //! \param target the destination BufferedTransformation 01556 //! \param copyMax the number of bytes to copy 01557 //! \param channel the channel on which the transfer should occur 01558 //! \returns the number of bytes copied during the call. 01559 //! \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object. 01560 //! \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2. 01561 lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const 01562 {return CopyRangeTo(target, 0, copyMax, channel);} 01563 01564 //! \brief Copy bytes from this object using an index to another BufferedTransformation 01565 //! \param target the destination BufferedTransformation 01566 //! \param position the 0-based index of the byte stream to begin the copying 01567 //! \param copyMax the number of bytes to copy 01568 //! \param channel the channel on which the transfer should occur 01569 //! \returns the number of bytes copied during the call. 01570 //! \details CopyTo copies bytes from this object to the destination. The bytes remain in this 01571 //! object. Copying begins at the index position in the current stream, and not from an absolute 01572 //! position in the stream. 01573 //! \details The function returns the new position in the stream after transferring the bytes starting at the index. 01574 lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const 01575 {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;} 01576 01577 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 01578 unsigned long MaxRetrieveable() const {return MaxRetrievable();} 01579 #endif 01580 //@} 01581 01582 //! \name RETRIEVAL OF MULTIPLE MESSAGES 01583 //@{ 01584 01585 //! \brief Provides the number of bytes ready for retrieval 01586 //! \returns the number of bytes ready for retrieval 01587 virtual lword TotalBytesRetrievable() const; 01588 01589 //! \brief Provides the number of meesages processed by this object 01590 //! \returns the number of meesages processed by this object 01591 //! \details NumberOfMessages returns number of times MessageEnd() has been 01592 //! received minus messages retrieved or skipped 01593 virtual unsigned int NumberOfMessages() const; 01594 01595 //! \brief Determines if any messages are available for retrieval 01596 //! \returns true if <tt>NumberOfMessages() > 0</tt>, false otherwise 01597 //! \details AnyMessages returns true if <tt>NumberOfMessages() > 0</tt> 01598 virtual bool AnyMessages() const; 01599 01600 //! \brief Start retrieving the next message 01601 //! \returns true if a message is ready for retrieval 01602 //! \details GetNextMessage() returns true if a message is ready for retrieval; false 01603 //! if no more messages exist or this message is not completely retrieved. 01604 virtual bool GetNextMessage(); 01605 01606 //! \brief Skip a number of meessages 01607 //! \returns 0 if the requested number of messages was skipped, non-0 otherwise 01608 //! \details SkipMessages() skips count number of messages. If there is an AttachedTransformation() 01609 //! then SkipMessages() is called on the attached transformation. If there is no attached 01610 //! transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo(). 01611 virtual unsigned int SkipMessages(unsigned int count=UINT_MAX); 01612 01613 //! \brief Transfer messages from this object to another BufferedTransformation 01614 //! \param target the destination BufferedTransformation 01615 //! \param count the number of messages to transfer 01616 //! \param channel the channel on which the transfer should occur 01617 //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 01618 //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination. 01619 //! If all bytes are not transferred for a message, then processing stops and the number of remaining 01620 //! bytes is returned. TransferMessagesTo() does not proceed to the next message. 01621 //! \details A return value of 0 indicates all messages were successfully transferred. 01622 unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) 01623 {TransferMessagesTo2(target, count, channel); return count;} 01624 01625 //! \brief Copies messages from this object to another BufferedTransformation 01626 //! \param target the destination BufferedTransformation 01627 //! \param count the number of messages to transfer 01628 //! \param channel the channel on which the transfer should occur 01629 //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 01630 //! \details CopyMessagesTo copies messages from this object and copies them to the destination. 01631 //! If all bytes are not transferred for a message, then processing stops and the number of remaining 01632 //! bytes is returned. CopyMessagesTo() does not proceed to the next message. 01633 //! \details A return value of 0 indicates all messages were successfully copied. 01634 unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const; 01635 01636 //! 01637 virtual void SkipAll(); 01638 //! 01639 void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) 01640 {TransferAllTo2(target, channel);} 01641 //! 01642 void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const; 01643 01644 virtual bool GetNextMessageSeries() {return false;} 01645 virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();} 01646 virtual unsigned int NumberOfMessageSeries() const {return 0;} 01647 //@} 01648 01649 //! \name NON-BLOCKING TRANSFER OF OUTPUT 01650 //@{ 01651 01652 // upon return, byteCount contains number of bytes that have finished being transfered, 01653 // and returns the number of bytes left in the current transfer block 01654 01655 //! \brief Transfer bytes from this object to another BufferedTransformation 01656 //! \param target the destination BufferedTransformation 01657 //! \param byteCount the number of bytes to transfer 01658 //! \param channel the channel on which the transfer should occur 01659 //! \param blocking specifies whether the object should block when processing input 01660 //! \returns the number of bytes that remain in the transfer block (i.e., bytes not transferred) 01661 //! \details TransferTo removes bytes from this object and moves them to the destination. 01662 //! Transfer begins at the index position in the current stream, and not from an absolute 01663 //! position in the stream. 01664 //! \details byteCount is an \a IN and \a OUT parameter. When the call is made, 01665 //! byteCount is the requested size of the transfer. When the call returns, byteCount is 01666 //! the number of bytes that were transferred. 01667 virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0; 01668 01669 // upon return, begin contains the start position of data yet to be finished copying, 01670 // and returns the number of bytes left in the current transfer block 01671 01672 //! \brief Copy bytes from this object to another BufferedTransformation 01673 //! \param target the destination BufferedTransformation 01674 //! \param begin the 0-based index of the first byte to copy in the stream 01675 //! \param end the 0-based index of the last byte to copy in the stream 01676 //! \param channel the channel on which the transfer should occur 01677 //! \param blocking specifies whether the object should block when processing input 01678 //! \returns the number of bytes that remain in the copy block (i.e., bytes not copied) 01679 //! \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not 01680 //! removed from this object. Copying begins at the index position in the current stream, and 01681 //! not from an absolute position in the stream. 01682 //! \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the 01683 //! starting position of the copy. When the call returns, begin is the position of the first 01684 //! byte that was \a not copied (which may be different tahn end). begin can be used for 01685 //! subsequent calls to CopyRangeTo2. 01686 virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0; 01687 01688 // upon return, messageCount contains number of messages that have finished being transfered, 01689 // and returns the number of bytes left in the current transfer block 01690 01691 //! \brief Transfer messages from this object to another BufferedTransformation 01692 //! \param target the destination BufferedTransformation 01693 //! \param messageCount the number of messages to transfer 01694 //! \param channel the channel on which the transfer should occur 01695 //! \param blocking specifies whether the object should block when processing input 01696 //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 01697 //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination. 01698 size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true); 01699 01700 // returns the number of bytes left in the current transfer block 01701 01702 //! \brief Transfer all bytes from this object to another BufferedTransformation 01703 //! \param target the destination BufferedTransformation 01704 //! \param channel the channel on which the transfer should occur 01705 //! \param blocking specifies whether the object should block when processing input 01706 //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 01707 //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination. 01708 size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true); 01709 //@} 01710 01711 //! \name CHANNELS 01712 //@{ 01713 //! \brief Exception thrown when a filter does not support named channels 01714 struct NoChannelSupport : public NotImplemented 01715 {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}}; 01716 //! \brief Exception thrown when a filter does not recognize a named channel 01717 struct InvalidChannelName : public InvalidArgument 01718 {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}}; 01719 01720 //! \brief Input a byte for processing on a channel 01721 //! \param channel the channel to process the data. 01722 //! \param inByte the 8-bit byte (octet) to be processed. 01723 //! \param blocking specifies whether the object should block when processing input. 01724 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01725 //! number of bytes that were \a not processed. 01726 size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true) 01727 {return ChannelPut(channel, &inByte, 1, blocking);} 01728 01729 //! \brief Input a byte buffer for processing on a channel 01730 //! \param channel the channel to process the data 01731 //! \param inString the byte buffer to process 01732 //! \param length the size of the string, in bytes 01733 //! \param blocking specifies whether the object should block when processing input 01734 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01735 //! number of bytes that were \a not processed. 01736 size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true) 01737 {return ChannelPut2(channel, inString, length, 0, blocking);} 01738 01739 //! \brief Input multiple bytes that may be modified by callee on a channel 01740 //! \param channel the channel to process the data. 01741 //! \param inString the byte buffer to process 01742 //! \param length the size of the string, in bytes 01743 //! \param blocking specifies whether the object should block when processing input 01744 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01745 //! number of bytes that were \a not processed. 01746 size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true) 01747 {return ChannelPutModifiable2(channel, inString, length, 0, blocking);} 01748 01749 //! \brief Input a 16-bit word for processing on a channel. 01750 //! \param channel the channel to process the data. 01751 //! \param value the 16-bit value to be processed. 01752 //! \param order the ByteOrder in which the word should be processed. 01753 //! \param blocking specifies whether the object should block when processing input. 01754 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01755 //! number of bytes that were \a not processed. 01756 size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 01757 01758 //! \brief Input a 32-bit word for processing on a channel. 01759 //! \param channel the channel to process the data. 01760 //! \param value the 32-bit value to be processed. 01761 //! \param order the ByteOrder in which the word should be processed. 01762 //! \param blocking specifies whether the object should block when processing input. 01763 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01764 //! number of bytes that were \a not processed. 01765 size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 01766 01767 //! \brief Signal the end of a message 01768 //! \param channel the channel to process the data. 01769 //! \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed 01770 //! \param blocking specifies whether the object should block when processing input 01771 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01772 //! number of bytes that were \a not processed. 01773 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01774 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01775 bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true) 01776 {return !!ChannelPut2(channel, NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);} 01777 01778 //! \brief Input multiple bytes for processing and signal the end of a message 01779 //! \param channel the channel to process the data. 01780 //! \param inString the byte buffer to process 01781 //! \param length the size of the string, in bytes 01782 //! \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed 01783 //! \param blocking specifies whether the object should block when processing input 01784 //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the 01785 //! number of bytes that were \a not processed. 01786 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01787 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01788 size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true) 01789 {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);} 01790 01791 //! \brief Request space which can be written into by the caller 01792 //! \param channel the channel to process the data 01793 //! \param size the requested size of the buffer 01794 //! \details The purpose of this method is to help avoid extra memory allocations. 01795 //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made, 01796 //! size is the requested size of the buffer. When the call returns, size is the size of 01797 //! the array returned to the caller. 01798 //! \details The base class implementation sets size to 0 and returns NULL. 01799 //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of 01800 //! an ArraySink, the pointer to the array is returned and the size is remaining size. 01801 virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size); 01802 01803 //! \brief Input multiple bytes for processing on a channel. 01804 //! \param channel the channel to process the data. 01805 //! \param inString the byte buffer to process. 01806 //! \param length the size of the string, in bytes. 01807 //! \param messageEnd means how many filters to signal MessageEnd() to, including this one. 01808 //! \param blocking specifies whether the object should block when processing input. 01809 virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking); 01810 01811 //! \brief Input multiple bytes that may be modified by callee on a channel 01812 //! \param channel the channel to process the data 01813 //! \param inString the byte buffer to process 01814 //! \param length the size of the string, in bytes 01815 //! \param messageEnd means how many filters to signal MessageEnd() to, including this one 01816 //! \param blocking specifies whether the object should block when processing input 01817 virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking); 01818 01819 //! \brief Flush buffered input and/or output on a channel 01820 //! \param channel the channel to flush the data 01821 //! \param hardFlush is used to indicate whether all data should be flushed 01822 //! \param propagation the number of attached transformations the ChannelFlush() signal should be passed 01823 //! \param blocking specifies whether the object should block when processing input 01824 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01825 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01826 virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true); 01827 01828 //! \brief Marks the end of a series of messages on a channel 01829 //! \param channel the channel to signal the end of a series of messages 01830 //! \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed 01831 //! \param blocking specifies whether the object should block when processing input 01832 //! \details Each object that receives the signal will perform its processing, decrement 01833 //! propagation, and then pass the signal on to attached transformations if the value is not 0. 01834 //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 01835 //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 01836 //! \note There should be a MessageEnd() immediately before MessageSeriesEnd(). 01837 virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true); 01838 01839 //! \brief Sets the default retrieval channel 01840 //! \param channel the channel to signal the end of a series of messages 01841 //! \note this function may not be implemented in all objects that should support it. 01842 virtual void SetRetrievalChannel(const std::string &channel); 01843 //@} 01844 01845 //! \name ATTACHMENT 01846 /*! Some BufferedTransformation objects (e.g. Filter objects) 01847 allow other BufferedTransformation objects to be attached. When 01848 this is done, the first object instead of buffering its output, 01849 sends that output to the attached object as input. The entire 01850 attachment chain is deleted when the anchor object is destructed. 01851 */ 01852 //@{ 01853 //! \brief Determines whether the object allows attachment 01854 //! \returns true if the object allows an attachment, false otherwise 01855 //! \details Sources and Filters will return true, while Sinks and other objects will return false. 01856 virtual bool Attachable() {return false;} 01857 01858 //! \brief Returns the object immediately attached to this object 01859 //! \details AttachedTransformation returns NULL if there is no attachment 01860 virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;} 01861 01862 //! \brief Returns the object immediately attached to this object 01863 //! \details AttachedTransformation returns NULL if there is no attachment 01864 virtual const BufferedTransformation *AttachedTransformation() const 01865 {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();} 01866 01867 //! \brief Delete the current attachment chain and attach a new one 01868 //! \param newAttachment the new BufferedTransformation to attach 01869 //! \throws NotImplemented 01870 //! \details Detach delete the current attachment chain and replace it with an optional newAttachment 01871 //! \details If a derived class does not override Detach, then the base class throws 01872 //! NotImplemented. 01873 virtual void Detach(BufferedTransformation *newAttachment = 0) { 01874 CRYPTOPP_UNUSED(newAttachment); assert(!Attachable()); 01875 throw NotImplemented("BufferedTransformation: this object is not attachable"); 01876 } 01877 01878 //! \brief Add newAttachment to the end of attachment chain 01879 //! \param newAttachment the attachment to add to the end of the chain 01880 01881 virtual void Attach(BufferedTransformation *newAttachment); 01882 //@} 01883 01884 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 01885 virtual ~BufferedTransformation() {} 01886 #endif 01887 01888 protected: 01889 //! \brief Decrements the propagation count while clamping at 0 01890 //! \returns the decremented propagation or 0 01891 static int DecrementPropagation(int propagation) 01892 {return propagation != 0 ? propagation - 1 : 0;} 01893 01894 private: 01895 byte m_buf[4]; // for ChannelPutWord16 and ChannelPutWord32, to ensure buffer isn't deallocated before non-blocking operation completes 01896 }; 01897 01898 //! \brief An input discarding BufferedTransformation 01899 //! \returns a reference to a BufferedTransformation object that discards all input 01900 CRYPTOPP_DLL BufferedTransformation & TheBitBucket(); 01901 01902 //! \class CryptoMaterial 01903 //! \brief Interface for crypto material, such as public and private keys, and crypto parameters 01904 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs 01905 { 01906 public: 01907 //! exception thrown when invalid crypto material is detected 01908 class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat 01909 { 01910 public: 01911 explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {} 01912 }; 01913 01914 //! \brief Assign values to this object 01915 /*! \details This function can be used to create a public key from a private key. */ 01916 virtual void AssignFrom(const NameValuePairs &source) =0; 01917 01918 //! \brief Check this object for errors 01919 //! \param rng a RandomNumberGenerator for objects which use randomized testing 01920 //! \param level the level of thoroughness 01921 //! \returns true if the tests succeed, false otherwise 01922 //! \details There are four levels of thoroughness: 01923 //! <ul> 01924 //! <li>0 - using this object won't cause a crash or exception 01925 //! <li>1 - this object will probably function, and encrypt, sign, other operations correctly 01926 //! <li>2 - ensure this object will function correctly, and perform reasonable security checks 01927 //! <li>3 - perform reasonable security checks, and do checks that may take a long time 01928 //! </ul> 01929 //! \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0. 01930 //! \details Level 1 may not check for weak keys and such. 01931 //! \details Levels 2 and 3 are recommended. 01932 virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0; 01933 01934 //! \brief Check this object for errors 01935 //! \param rng a RandomNumberGenerator for objects which use randomized testing 01936 //! \param level the level of thoroughness 01937 //! \throws InvalidMaterial 01938 //! \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial if validation fails. 01939 virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const 01940 {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");} 01941 01942 //! \brief Saves a key to a BufferedTransformation 01943 //! \param bt the destination BufferedTransformation 01944 //! \throws NotImplemented 01945 //! \details Save writes the material to a BufferedTransformation. 01946 //! \details If the material is a key, then the key is written with ASN.1 DER encoding. The key 01947 //! includes an object identifier with an algorthm id, like a subjectPublicKeyInfo. 01948 //! \details A "raw" key without the "key info" can be saved using a key's DEREncode method. 01949 //! \details If a derived class does not override Save, then the base class throws 01950 //! NotImplemented. 01951 virtual void Save(BufferedTransformation &bt) const 01952 {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");} 01953 01954 //! \brief Loads a key from a BufferedTransformation 01955 //! \param bt the source BufferedTransformation 01956 //! \throws KeyingErr 01957 //! \details Load attempts to read material from a BufferedTransformation. If the 01958 //! material is a key that was generated outside the library, then the following 01959 //! usually applies: 01960 //! <ul> 01961 //! <li>the key should be ASN.1 BER encoded 01962 //! <li>the key should be a "key info" 01963 //! </ul> 01964 //! \details "key info" means the key should have an object identifier with an algorthm id, 01965 //! like a subjectPublicKeyInfo. 01966 //! \details To read a "raw" key without the "key info", then call the key's BERDecode method. 01967 //! \note Load generally does not check that the key is valid. Call Validate(), if needed. 01968 virtual void Load(BufferedTransformation &bt) 01969 {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");} 01970 01971 //! \brief Determines whether the object supports precomputation 01972 //! \returns true if the object supports precomputation, false otherwise 01973 virtual bool SupportsPrecomputation() const {return false;} 01974 01975 //! \brief Perform precomputation 01976 //! \param precomputationStorage the suggested number of objects for the precompute table 01977 //! \throws NotImplemented 01978 //! \details The exact semantics of Precompute() varies, but it typically means calculate 01979 //! a table of n objects that can be used later to speed up computation. 01980 //! \details If a derived class does not override Precompute, then the base class throws 01981 //! NotImplemented. 01982 virtual void Precompute(unsigned int precomputationStorage) { 01983 CRYPTOPP_UNUSED(precomputationStorage); assert(!SupportsPrecomputation()); 01984 throw NotImplemented("CryptoMaterial: this object does not support precomputation"); 01985 } 01986 01987 //! retrieve previously saved precomputation 01988 virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation) 01989 {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} 01990 //! save precomputation for later use 01991 virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const 01992 {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} 01993 01994 // for internal library use 01995 void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);} 01996 01997 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 01998 virtual ~CryptoMaterial() {} 01999 #endif 02000 02001 #if (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) 02002 // Sun Studio 11/CC 5.8 workaround: it generates incorrect code when casting to an empty virtual base class 02003 char m_sunCCworkaround; 02004 #endif 02005 }; 02006 02007 //! \class GeneratableCryptoMaterial 02008 //! \brief Interface for generatable crypto material, such as private keys and crypto parameters 02009 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial 02010 { 02011 public: 02012 02013 //! \brief Generate a random key or crypto parameters 02014 //! \param rng a RandomNumberGenerator to produce keying material 02015 //! \param params additional initialization parameters 02016 //! \throws KeyingErr if a key can't be generated or algorithm parameters are invalid 02017 //! \details If a derived class does not override GenerateRandom, then the base class throws 02018 //! NotImplemented. 02019 virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶ms = g_nullNameValuePairs) { 02020 CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params); 02021 throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation"); 02022 } 02023 02024 //! \brief Generate a random key or crypto parameters 02025 //! \param rng a RandomNumberGenerator to produce keying material 02026 //! \param keySize the size of the key, in bits 02027 //! \throws KeyingErr if a key can't be generated or algorithm parameters are invalid 02028 //! \details GenerateRandomWithKeySize calls GenerateRandom with a NameValuePairs 02029 //! object with only "KeySize" 02030 void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize); 02031 02032 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02033 virtual ~GeneratableCryptoMaterial() {} 02034 #endif 02035 }; 02036 02037 //! \brief Interface for public keys 02038 02039 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial 02040 { 02041 }; 02042 02043 //! \brief Interface for private keys 02044 02045 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial 02046 { 02047 }; 02048 02049 //! \brief Interface for crypto prameters 02050 02051 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial 02052 { 02053 }; 02054 02055 //! \brief Interface for asymmetric algorithms 02056 02057 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm 02058 { 02059 public: 02060 //! returns a reference to the crypto material used by this object 02061 virtual CryptoMaterial & AccessMaterial() =0; 02062 //! returns a const reference to the crypto material used by this object 02063 virtual const CryptoMaterial & GetMaterial() const =0; 02064 02065 //! for backwards compatibility, calls AccessMaterial().Load(bt) 02066 void BERDecode(BufferedTransformation &bt) 02067 {AccessMaterial().Load(bt);} 02068 //! for backwards compatibility, calls GetMaterial().Save(bt) 02069 void DEREncode(BufferedTransformation &bt) const 02070 {GetMaterial().Save(bt);} 02071 02072 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02073 virtual ~AsymmetricAlgorithm() {} 02074 #endif 02075 }; 02076 02077 //! \brief Interface for asymmetric algorithms using public keys 02078 02079 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm 02080 { 02081 public: 02082 // VC60 workaround: no co-variant return type 02083 CryptoMaterial & AccessMaterial() {return AccessPublicKey();} 02084 const CryptoMaterial & GetMaterial() const {return GetPublicKey();} 02085 02086 virtual PublicKey & AccessPublicKey() =0; 02087 virtual const PublicKey & GetPublicKey() const {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();} 02088 02089 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02090 virtual ~PublicKeyAlgorithm() {} 02091 #endif 02092 }; 02093 02094 //! \brief Interface for asymmetric algorithms using private keys 02095 02096 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm 02097 { 02098 public: 02099 CryptoMaterial & AccessMaterial() {return AccessPrivateKey();} 02100 const CryptoMaterial & GetMaterial() const {return GetPrivateKey();} 02101 02102 virtual PrivateKey & AccessPrivateKey() =0; 02103 virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();} 02104 02105 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02106 virtual ~PrivateKeyAlgorithm() {} 02107 #endif 02108 }; 02109 02110 //! \brief Interface for key agreement algorithms 02111 02112 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm 02113 { 02114 public: 02115 CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();} 02116 const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();} 02117 02118 virtual CryptoParameters & AccessCryptoParameters() =0; 02119 virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();} 02120 02121 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02122 virtual ~KeyAgreementAlgorithm() {} 02123 #endif 02124 }; 02125 02126 //! \brief Interface for public-key encryptors and decryptors 02127 02128 /*! This class provides an interface common to encryptors and decryptors 02129 for querying their plaintext and ciphertext lengths. 02130 */ 02131 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem 02132 { 02133 public: 02134 virtual ~PK_CryptoSystem() {} 02135 02136 //! maximum length of plaintext for a given ciphertext length 02137 /*! \note This function returns 0 if ciphertextLength is not valid (too long or too short). */ 02138 virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0; 02139 02140 //! calculate length of ciphertext given length of plaintext 02141 /*! \note This function returns 0 if plaintextLength is not valid (too long). */ 02142 virtual size_t CiphertextLength(size_t plaintextLength) const =0; 02143 02144 //! this object supports the use of the parameter with the given name 02145 /*! some possible parameter names: EncodingParameters, KeyDerivationParameters */ 02146 virtual bool ParameterSupported(const char *name) const =0; 02147 02148 //! return fixed ciphertext length, if one exists, otherwise return 0 02149 /*! \note "Fixed" here means length of ciphertext does not depend on length of plaintext. 02150 It usually does depend on the key length. */ 02151 virtual size_t FixedCiphertextLength() const {return 0;} 02152 02153 //! return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0 02154 virtual size_t FixedMaxPlaintextLength() const {return 0;} 02155 02156 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 02157 size_t MaxPlainTextLength(size_t cipherTextLength) const {return MaxPlaintextLength(cipherTextLength);} 02158 size_t CipherTextLength(size_t plainTextLength) const {return CiphertextLength(plainTextLength);} 02159 #endif 02160 }; 02161 02162 //! \class PK_Encryptor 02163 //! \brief Interface for public-key encryptors 02164 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm 02165 { 02166 public: 02167 //! \brief Exception thrown when trying to encrypt plaintext of invalid length 02168 class CRYPTOPP_DLL InvalidPlaintextLength : public Exception 02169 { 02170 public: 02171 InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {} 02172 }; 02173 02174 //! \brief Encrypt a byte string 02175 //! \param rng a RandomNumberGenerator derived class 02176 //! \param plaintext the plaintext byte buffer 02177 //! \param plaintextLength the size of the plaintext byte buffer 02178 //! \param ciphertext a byte buffer to hold the encrypted string 02179 //! \param parameters additional configuration options 02180 //! \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large 02181 //! \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output 02182 //! byte buffer is large enough. 02183 //! \sa PK_Decryptor 02184 virtual void Encrypt(RandomNumberGenerator &rng, 02185 const byte *plaintext, size_t plaintextLength, 02186 byte *ciphertext, const NameValuePairs ¶meters = g_nullNameValuePairs) const =0; 02187 02188 //! \brief Create a new encryption filter 02189 //! \note The caller is responsible for deleting the returned pointer. 02190 //! \note Encoding parameters should be passed in the "EP" channel. 02191 virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, 02192 BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters = g_nullNameValuePairs) const; 02193 }; 02194 02195 //! \class PK_Decryptor 02196 //! \brief Interface for public-key decryptors 02197 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm 02198 { 02199 public: 02200 //! \brief Decrypt a byte string 02201 //! \param rng a RandomNumberGenerator derived class 02202 //! \param ciphertext the encrypted byte buffer 02203 //! \param ciphertextLength the size of the encrypted byte buffer 02204 //! \param plaintext a byte buffer to hold the decrypted string 02205 //! \param parameters additional configuration options 02206 //! \returns the result of the decryption operation 02207 //! \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output 02208 //! byte buffer is large enough 02209 //! \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength 02210 //! is valid and holds the the actual length of the plaintext recovered. 02211 //! on success. The result is undefined if decryption failed. If DecodingResult::isValidCoding 02212 //! is false, then DecodingResult::messageLength is undefined. 02213 //! \sa PK_Encryptor 02214 virtual DecodingResult Decrypt(RandomNumberGenerator &rng, 02215 const byte *ciphertext, size_t ciphertextLength, 02216 byte *plaintext, const NameValuePairs ¶meters = g_nullNameValuePairs) const =0; 02217 02218 //! create a new decryption filter 02219 /*! \note caller is responsible for deleting the returned pointer 02220 */ 02221 virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, 02222 BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters = g_nullNameValuePairs) const; 02223 02224 //! decrypt a fixed size ciphertext 02225 DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs ¶meters = g_nullNameValuePairs) const 02226 {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);} 02227 02228 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02229 virtual ~PK_Decryptor() {} 02230 #endif 02231 }; 02232 02233 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 02234 typedef PK_CryptoSystem PK_FixedLengthCryptoSystem; 02235 typedef PK_Encryptor PK_FixedLengthEncryptor; 02236 typedef PK_Decryptor PK_FixedLengthDecryptor; 02237 #endif 02238 02239 //! \brief Interface for public-key signers and verifiers 02240 02241 /*! This class provides an interface common to signers and verifiers 02242 for querying scheme properties. 02243 */ 02244 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme 02245 { 02246 public: 02247 //! 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 02248 class CRYPTOPP_DLL InvalidKeyLength : public Exception 02249 { 02250 public: 02251 InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {} 02252 }; 02253 02254 //! 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 02255 class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength 02256 { 02257 public: 02258 KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {} 02259 }; 02260 02261 virtual ~PK_SignatureScheme() {} 02262 02263 //! signature length if it only depends on the key, otherwise 0 02264 virtual size_t SignatureLength() const =0; 02265 02266 //! maximum signature length produced for a given length of recoverable message part 02267 virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const 02268 {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();} 02269 02270 //! length of longest message that can be recovered, or 0 if this signature scheme does not support message recovery 02271 virtual size_t MaxRecoverableLength() const =0; 02272 02273 //! 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 02274 virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0; 02275 02276 //! requires a random number generator to sign 02277 /*! if this returns false, NullRNG() can be passed to functions that take RandomNumberGenerator & */ 02278 virtual bool IsProbabilistic() const =0; 02279 02280 //! whether or not a non-recoverable message part can be signed 02281 virtual bool AllowNonrecoverablePart() const =0; 02282 02283 //! if this function returns true, during verification you must input the signature before the message, otherwise you can input it at anytime */ 02284 virtual bool SignatureUpfront() const {return false;} 02285 02286 //! whether you must input the recoverable part before the non-recoverable part during signing 02287 virtual bool RecoverablePartFirst() const =0; 02288 }; 02289 02290 //! \brief Interface for accumulating messages to be signed or verified 02291 /*! Only Update() should be called 02292 on this class. No other functions inherited from HashTransformation should be called. 02293 */ 02294 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation 02295 { 02296 public: 02297 //! should not be called on PK_MessageAccumulator 02298 unsigned int DigestSize() const 02299 {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");} 02300 02301 //! should not be called on PK_MessageAccumulator 02302 void TruncatedFinal(byte *digest, size_t digestSize) 02303 { 02304 CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize); 02305 throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called"); 02306 } 02307 }; 02308 02309 //! \brief Interface for public-key signers 02310 02311 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm 02312 { 02313 public: 02314 //! create a new HashTransformation to accumulate the message to be signed 02315 virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0; 02316 02317 virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0; 02318 02319 //! sign and delete messageAccumulator (even in case of exception thrown) 02320 /*! \pre size of signature == MaxSignatureLength() 02321 \returns actual signature length 02322 */ 02323 virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const; 02324 02325 //! sign and restart messageAccumulator 02326 /*! \pre size of signature == MaxSignatureLength() 02327 \returns actual signature length 02328 */ 02329 virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0; 02330 02331 //! sign a message 02332 /*! \pre size of signature == MaxSignatureLength() 02333 \returns actual signature length 02334 */ 02335 virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const; 02336 02337 //! sign a recoverable message 02338 /*! \pre size of signature == MaxSignatureLength(recoverableMessageLength) 02339 \returns actual signature length 02340 */ 02341 virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength, 02342 const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const; 02343 02344 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02345 virtual ~PK_Signer() {} 02346 #endif 02347 }; 02348 02349 //! \brief Interface for public-key signature verifiers 02350 /*! The Recover* functions throw NotImplemented if the signature scheme does not support 02351 message recovery. 02352 The Verify* functions throw InvalidDataFormat if the scheme does support message 02353 recovery and the signature contains a non-empty recoverable message part. The 02354 Recovery* functions should be used in that case. 02355 */ 02356 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm 02357 { 02358 public: 02359 //! create a new HashTransformation to accumulate the message to be verified 02360 virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0; 02361 02362 //! input signature into a message accumulator 02363 virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0; 02364 02365 //! check whether messageAccumulator contains a valid signature and message, and delete messageAccumulator (even in case of exception thrown) 02366 virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const; 02367 02368 //! check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator 02369 virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0; 02370 02371 //! check whether input signature is a valid signature for input message 02372 virtual bool VerifyMessage(const byte *message, size_t messageLen, 02373 const byte *signature, size_t signatureLength) const; 02374 02375 //! recover a message from its signature 02376 /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength) 02377 */ 02378 virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const; 02379 02380 //! recover a message from its signature 02381 /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength) 02382 */ 02383 virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0; 02384 02385 //! recover a message from its signature 02386 /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength) 02387 */ 02388 virtual DecodingResult RecoverMessage(byte *recoveredMessage, 02389 const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, 02390 const byte *signature, size_t signatureLength) const; 02391 02392 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02393 virtual ~PK_Verifier() {} 02394 #endif 02395 }; 02396 02397 //! \brief Interface for domains of simple key agreement protocols 02398 02399 /*! A key agreement domain is a set of parameters that must be shared 02400 by two parties in a key agreement protocol, along with the algorithms 02401 for generating key pairs and deriving agreed values. 02402 */ 02403 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm 02404 { 02405 public: 02406 //! return length of agreed value produced 02407 virtual unsigned int AgreedValueLength() const =0; 02408 //! return length of private keys in this domain 02409 virtual unsigned int PrivateKeyLength() const =0; 02410 //! return length of public keys in this domain 02411 virtual unsigned int PublicKeyLength() const =0; 02412 //! generate private key 02413 /*! \pre size of privateKey == PrivateKeyLength() */ 02414 virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 02415 //! generate public key 02416 /*! re size of publicKey == PublicKeyLength() */ 02417 virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 02418 //! generate private/public key pair 02419 /*! \note equivalent to calling GeneratePrivateKey() and then GeneratePublicKey() */ 02420 virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 02421 //! derive agreed value from your private key and couterparty's public key, return false in case of failure 02422 /*! \note If you have previously validated the public key, use validateOtherPublicKey=false to save time. 02423 re size of agreedValue == AgreedValueLength() 02424 \pre length of privateKey == PrivateKeyLength() 02425 \pre length of otherPublicKey == PublicKeyLength() 02426 */ 02427 virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0; 02428 02429 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02430 virtual ~SimpleKeyAgreementDomain() {} 02431 #endif 02432 02433 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 02434 bool ValidateDomainParameters(RandomNumberGenerator &rng) const 02435 {return GetCryptoParameters().Validate(rng, 2);} 02436 #endif 02437 }; 02438 02439 //! \brief Interface for domains of authenticated key agreement protocols 02440 02441 /*! In an authenticated key agreement protocol, each party has two 02442 key pairs. The long-lived key pair is called the static key pair, 02443 and the short-lived key pair is called the ephemeral key pair. 02444 */ 02445 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm 02446 { 02447 public: 02448 //! return length of agreed value produced 02449 virtual unsigned int AgreedValueLength() const =0; 02450 02451 //! return length of static private keys in this domain 02452 virtual unsigned int StaticPrivateKeyLength() const =0; 02453 //! return length of static public keys in this domain 02454 virtual unsigned int StaticPublicKeyLength() const =0; 02455 //! generate static private key 02456 /*! \pre size of privateKey == PrivateStaticKeyLength() */ 02457 virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 02458 //! generate static public key 02459 /*! re size of publicKey == PublicStaticKeyLength() */ 02460 virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 02461 //! generate private/public key pair 02462 /*! \note equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey() */ 02463 virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 02464 02465 //! return length of ephemeral private keys in this domain 02466 virtual unsigned int EphemeralPrivateKeyLength() const =0; 02467 //! return length of ephemeral public keys in this domain 02468 virtual unsigned int EphemeralPublicKeyLength() const =0; 02469 //! \brief Generate ephemeral private key 02470 //! \pre size of privateKey == PrivateEphemeralKeyLength() 02471 virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 02472 //! \brief Generate ephemeral public key 02473 //! \pre size of publicKey == PublicEphemeralKeyLength() 02474 virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 02475 //! \brief Generate private/public key pair 02476 /*! \note equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() */ 02477 virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 02478 02479 //! \brief Derive agreed value 02480 //! \returns true upon success, false in case of failure 02481 //! \details Agree() derives an agreed value from your private keys and couterparty's public keys 02482 //! \details The ephemeral public key will always be validated. If you have previously validated the 02483 //! static public key, use validateStaticOtherPublicKey=false to save time. 02484 //! \pre size of agreedValue == AgreedValueLength() 02485 //! \pre length of staticPrivateKey == StaticPrivateKeyLength() 02486 //! \pre length of ephemeralPrivateKey == EphemeralPrivateKeyLength() 02487 //! \pre length of staticOtherPublicKey == StaticPublicKeyLength() 02488 //! \pre length of ephemeralOtherPublicKey == EphemeralPublicKeyLength() 02489 virtual bool Agree(byte *agreedValue, 02490 const byte *staticPrivateKey, const byte *ephemeralPrivateKey, 02491 const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey, 02492 bool validateStaticOtherPublicKey=true) const =0; 02493 02494 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02495 virtual ~AuthenticatedKeyAgreementDomain() {} 02496 #endif 02497 02498 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 02499 bool ValidateDomainParameters(RandomNumberGenerator &rng) const 02500 {return GetCryptoParameters().Validate(rng, 2);} 02501 #endif 02502 }; 02503 02504 // interface for password authenticated key agreement protocols, not implemented yet 02505 #if 0 02506 //! \brief Interface for protocol sessions 02507 /*! The methods should be called in the following order: 02508 02509 InitializeSession(rng, parameters); // or call initialize method in derived class 02510 while (true) 02511 { 02512 if (OutgoingMessageAvailable()) 02513 { 02514 length = GetOutgoingMessageLength(); 02515 GetOutgoingMessage(message); 02516 ; // send outgoing message 02517 } 02518 02519 if (LastMessageProcessed()) 02520 break; 02521 02522 ; // receive incoming message 02523 ProcessIncomingMessage(message); 02524 } 02525 ; // call methods in derived class to obtain result of protocol session 02526 */ 02527 class ProtocolSession 02528 { 02529 public: 02530 //! exception thrown when an invalid protocol message is processed 02531 class ProtocolError : public Exception 02532 { 02533 public: 02534 ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {} 02535 }; 02536 02537 //! exception thrown when a function is called unexpectedly 02538 /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */ 02539 class UnexpectedMethodCall : public Exception 02540 { 02541 public: 02542 UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {} 02543 }; 02544 02545 ProtocolSession() : m_rng(NULL), m_throwOnProtocolError(true), m_validState(false) {} 02546 virtual ~ProtocolSession() {} 02547 02548 virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs ¶meters) =0; 02549 02550 bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;} 02551 void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;} 02552 02553 bool HasValidState() const {return m_validState;} 02554 02555 virtual bool OutgoingMessageAvailable() const =0; 02556 virtual unsigned int GetOutgoingMessageLength() const =0; 02557 virtual void GetOutgoingMessage(byte *message) =0; 02558 02559 virtual bool LastMessageProcessed() const =0; 02560 virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0; 02561 02562 protected: 02563 void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const; 02564 void CheckAndHandleInvalidState() const; 02565 void SetValidState(bool valid) {m_validState = valid;} 02566 02567 RandomNumberGenerator *m_rng; 02568 02569 private: 02570 bool m_throwOnProtocolError, m_validState; 02571 }; 02572 02573 class KeyAgreementSession : public ProtocolSession 02574 { 02575 public: 02576 virtual unsigned int GetAgreedValueLength() const =0; 02577 virtual void GetAgreedValue(byte *agreedValue) const =0; 02578 02579 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02580 virtual ~KeyAgreementSession() {} 02581 #endif 02582 }; 02583 02584 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession 02585 { 02586 public: 02587 void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng, 02588 const byte *myId, unsigned int myIdLength, 02589 const byte *counterPartyId, unsigned int counterPartyIdLength, 02590 const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength); 02591 02592 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02593 virtual ~PasswordAuthenticatedKeyAgreementSession() {} 02594 #endif 02595 }; 02596 02597 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm 02598 { 02599 public: 02600 //! return whether the domain parameters stored in this object are valid 02601 virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const 02602 {return GetCryptoParameters().Validate(rng, 2);} 02603 02604 virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0; 02605 virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0; 02606 02607 enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8}; 02608 02609 virtual bool IsValidRole(unsigned int role) =0; 02610 virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0; 02611 02612 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562 02613 virtual ~PasswordAuthenticatedKeyAgreementDomain() {} 02614 #endif 02615 }; 02616 #endif 02617 02618 //! \brief Exception thrown when an ASN1 BER decoing error is encountered 02619 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument 02620 { 02621 public: 02622 BERDecodeErr() : InvalidArgument("BER decode error") {} 02623 BERDecodeErr(const std::string &s) : InvalidArgument(s) {} 02624 }; 02625 02626 //! \brief Interface for encoding and decoding ASN1 objects 02627 //! \details Each class that derives from ASN1Object should provide a serialization format 02628 //! that controls subobject layout. Most of the time the serialization format is 02629 //! taken from a standard, like P1363 or an RFC. 02630 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object 02631 { 02632 public: 02633 virtual ~ASN1Object() {} 02634 02635 //! \brief Decode this object from a BufferedTransformation 02636 //! \param bt BufferedTransformation object 02637 //! \details Uses Basic Encoding Rules (BER) 02638 virtual void BERDecode(BufferedTransformation &bt) =0; 02639 02640 //! \brief Encode this object into a BufferedTransformation 02641 //! \param bt BufferedTransformation object 02642 //! \details Uses Distinguished Encoding Rules (DER) 02643 virtual void DEREncode(BufferedTransformation &bt) const =0; 02644 02645 //! \brief Encode this object into a BufferedTransformation 02646 //! \param bt BufferedTransformation object 02647 //! \details Uses Basic Encoding Rules (BER). 02648 //! \details This may be useful if DEREncode() would be too inefficient. 02649 virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);} 02650 }; 02651 02652 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY 02653 typedef PK_SignatureScheme PK_SignatureSystem; 02654 typedef SimpleKeyAgreementDomain PK_SimpleKeyAgreementDomain; 02655 typedef AuthenticatedKeyAgreementDomain PK_AuthenticatedKeyAgreementDomain; 02656 #endif 02657 02658 NAMESPACE_END 02659 02660 #if CRYPTOPP_MSC_VERSION 02661 # pragma warning(pop) 02662 #endif 02663 02664 #endif