|
||||
File indexing completed on 2025-01-18 09:54:56
0001 // cryptlib.h - originally written and placed in the public domain by Wei Dai 0002 0003 /// \file cryptlib.h 0004 /// \brief Abstract base classes that provide a uniform interface to this library. 0005 0006 /*! \mainpage Crypto++ Library 8.9 API Reference 0007 <dl> 0008 <dt>Abstract Base Classes<dd> 0009 cryptlib.h 0010 <dt>Authenticated Encryption Modes<dd> 0011 CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)" 0012 <dt>Block Ciphers<dd> 0013 \ref Rijndael "AES", ARIA, Weak::ARC4, Blowfish, BTEA, \ref CHAM128 "CHAM (64/128)", Camellia, 0014 \ref CAST128 "CAST (128/256)", DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", 0015 \ref DES_XEX3 "DESX", GOST, HIGHT, IDEA, LEA, \ref LR "Luby-Rackoff", \ref Kalyna128 "Kalyna (128/256/512)", 0016 MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent, 0017 \ref SHACAL2 "SHACAL-2", SHARK, \ref SIMECK64 "SIMECK (32/64)" SKIPJACK, SM4, Square, TEA, 0018 \ref ThreeWay "3-Way", \ref Threefish256 "Threefish (256/512/1024)", Twofish, XTEA 0019 <dt>Stream Ciphers<dd> 0020 \ref ChaCha "ChaCha (8/12/20)", \ref HC128 "HC-128/256", \ref Panama "Panama-LE", \ref Panama "Panama-BE", 0021 Rabbit, Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20 0022 <dt>Hash Functions<dd> 0023 BLAKE2s, BLAKE2b, \ref Keccak "Keccak (F1600)", SHA1, SHA224, SHA256, SHA384, SHA512, 0024 \ref SHA3 "SHA-3", SM3, LSH (256/512), Tiger, RIPEMD160, RIPEMD256, SipHash, Whirlpool, 0025 Weak::MD2, Weak::MD4, Weak::MD5 0026 <dt>Non-Cryptographic Checksums<dd> 0027 CRC32, CRC32C, Adler32 0028 <dt>Message Authentication Codes<dd> 0029 BLAKE2b, BLAKE2s, CBC_MAC, CMAC, DMAC, \ref GCM "GCM (GMAC)", HMAC, Poly1305, TTMAC, VMAC 0030 <dt>Random Number Generators<dd> 0031 NullRNG, LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG, 0032 NIST Hash_DRBG and HMAC_DRBG, \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)", 0033 DARN, RDRAND, RDSEED 0034 <dt>Key Derivation and Password-based Cryptography<dd> 0035 HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)", 0036 \ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)" 0037 <dt>Public Key Cryptosystems<dd> 0038 DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES 0039 <dt>Public Key Signature Schemes<dd> 0040 DSA, DSA2, \ref ed25519 "Ed25519", GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, 0041 RabinSS, RWSS, ESIGN 0042 <dt>Key Agreement<dd> 0043 DH, DH2, \ref x25519 "X25519", \ref MQV_Domain "MQV", \ref HMQV_Domain "HMQV", 0044 \ref FHMQV_Domain "FHMQV", ECDH, x25519, ECMQV, ECHMQV, ECFHMQV, XTR_DH 0045 <dt>Algebraic Structures<dd> 0046 Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver, 0047 ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP 0048 <dt>Secret Sharing and Information Dispersal<dd> 0049 SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery 0050 <dt>Compression<dd> 0051 Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor 0052 <dt>Input Source Classes<dd> 0053 StringSource, ArraySource, VectorSource, FileSource, RandomNumberSource 0054 <dt>Output Sink Classes<dd> 0055 StringSinkTemplate, StringSink, VectorSink, ArraySink, FileSink, RandomNumberSink 0056 <dt>Filter Wrappers<dd> 0057 StreamTransformationFilter, AuthenticatedEncryptionFilter, AuthenticatedDecryptionFilter, HashFilter, 0058 HashVerificationFilter, SignerFilter, SignatureVerificationFilter 0059 <dt>Binary to Text Encoders and Decoders<dd> 0060 HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder, 0061 Base32Decoder 0062 <dt>Wrappers for OS features<dd> 0063 Timer, ThreadUserTimer 0064 0065 </dl> 0066 0067 <!-- 0068 0069 <dt>FIPS 140 validated cryptography<dd> 0070 fips140.h 0071 0072 In the DLL version of Crypto++, only the following implementation class are available. 0073 <dl> 0074 <dt>Block Ciphers<dd> 0075 AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK 0076 <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd> 0077 \ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>", 0078 \ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>" 0079 <dt>Hash Functions<dd> 0080 SHA1, SHA224, SHA256, SHA384, SHA512 0081 <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd> 0082 RSASS\<PKCS1v15, H\>, RSASS\<PSS, H\>, RSASS_ISO\<H\>, RWSS\<P1363_EMSA2, H\>, DSA, ECDSA\<ECP, H\>, 0083 ECDSA\<EC2N, H\> 0084 <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd> 0085 HMAC\<H\>, CBC_MAC\<DES_EDE2\>, CBC_MAC\<DES_EDE3\>, GCM\<AES\> 0086 <dt>Random Number Generators<dd> 0087 DefaultAutoSeededRNG (AutoSeededX917RNG\<AES\>) 0088 <dt>Key Agreement<dd> 0089 DH, DH2 0090 <dt>Public Key Cryptosystems<dd> 0091 RSAES\<OAEP\<SHA1\> \> 0092 </dl> 0093 0094 --> 0095 0096 <p>This reference manual is a work in progress. Some classes lack detailed descriptions. 0097 <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual. 0098 <p>Thanks to Ryan Phillips for providing the Doxygen configuration file 0099 and getting us started on the manual. 0100 */ 0101 0102 #ifndef CRYPTOPP_CRYPTLIB_H 0103 #define CRYPTOPP_CRYPTLIB_H 0104 0105 #include "config.h" 0106 #include "stdcpp.h" 0107 #include "trap.h" 0108 0109 // C5264 new for VS2022/v17.4, MSC v17.3.4 0110 // https://github.com/weidai11/cryptopp/issues/1185 0111 #if CRYPTOPP_MSC_VERSION 0112 # pragma warning(push) 0113 # pragma warning(disable: 4127 4189 4505 4702) 0114 # if (CRYPTOPP_MSC_VERSION >= 1933) 0115 # pragma warning(disable: 5264) 0116 # endif 0117 #endif 0118 0119 NAMESPACE_BEGIN(CryptoPP) 0120 0121 // forward declarations 0122 class Integer; 0123 class RandomNumberGenerator; 0124 class BufferedTransformation; 0125 0126 /// \brief Specifies a direction for a cipher to operate 0127 /// \sa BlockTransformation::IsForwardTransformation(), BlockTransformation::IsPermutation(), BlockTransformation::GetCipherDirection() 0128 enum CipherDir { 0129 /// \brief the cipher is performing encryption 0130 ENCRYPTION, 0131 /// \brief the cipher is performing decryption 0132 DECRYPTION}; 0133 0134 /// \brief Represents infinite time 0135 CRYPTOPP_CONST_OR_CONSTEXPR unsigned long INFINITE_TIME = ULONG_MAX; 0136 0137 // VC60 workaround: using enums as template parameters causes problems 0138 /// \brief Converts an enumeration to a type suitable for use as a template parameter 0139 template <typename ENUM_TYPE, int VALUE> 0140 struct EnumToType 0141 { 0142 static ENUM_TYPE ToEnum() {return static_cast<ENUM_TYPE>(VALUE);} 0143 }; 0144 0145 /// \brief Provides the byte ordering 0146 /// \details Big-endian and little-endian modes are supported. Bi-endian and PDP-endian modes 0147 /// are not supported. 0148 enum ByteOrder { 0149 /// \brief byte order is little-endian 0150 LITTLE_ENDIAN_ORDER = 0, 0151 /// \brief byte order is big-endian 0152 BIG_ENDIAN_ORDER = 1}; 0153 0154 /// \brief Provides a constant for LittleEndian 0155 typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian; 0156 /// \brief Provides a constant for BigEndian 0157 typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian; 0158 0159 /// \brief Base class for all exceptions thrown by the library 0160 /// \details All library exceptions directly or indirectly inherit from the Exception class. 0161 /// The Exception class itself inherits from std::exception. The library does not use 0162 /// std::runtime_error derived classes. 0163 class CRYPTOPP_DLL Exception : public std::exception 0164 { 0165 public: 0166 /// \enum ErrorType 0167 /// \brief Error types or categories 0168 enum ErrorType { 0169 /// \brief A method was called which was not implemented 0170 NOT_IMPLEMENTED, 0171 /// \brief An invalid argument was detected 0172 INVALID_ARGUMENT, 0173 /// \brief BufferedTransformation received a Flush(true) signal but can't flush buffers 0174 CANNOT_FLUSH, 0175 /// \brief Data integerity check, such as CRC or MAC, failed 0176 DATA_INTEGRITY_CHECK_FAILED, 0177 /// \brief Input data was received that did not conform to expected format 0178 INVALID_DATA_FORMAT, 0179 /// \brief Error reading from input device or writing to output device 0180 IO_ERROR, 0181 /// \brief Some other error occurred not belonging to other categories 0182 OTHER_ERROR 0183 }; 0184 0185 virtual ~Exception() throw() {} 0186 0187 /// \brief Construct a new Exception 0188 explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {} 0189 0190 /// \brief Retrieves a C-string describing the exception 0191 const char *what() const throw() {return (m_what.c_str());} 0192 /// \brief Retrieves a string describing the exception 0193 const std::string &GetWhat() const {return m_what;} 0194 /// \brief Sets the error string for the exception 0195 void SetWhat(const std::string &s) {m_what = s;} 0196 /// \brief Retrieves the error type for the exception 0197 ErrorType GetErrorType() const {return m_errorType;} 0198 /// \brief Sets the error type for the exceptions 0199 void SetErrorType(ErrorType errorType) {m_errorType = errorType;} 0200 0201 private: 0202 ErrorType m_errorType; 0203 std::string m_what; 0204 }; 0205 0206 /// \brief An invalid argument was detected 0207 class CRYPTOPP_DLL InvalidArgument : public Exception 0208 { 0209 public: 0210 /// \brief Construct an InvalidArgument 0211 /// \param s the message for the exception 0212 /// \details The member function <tt>what()</tt> returns <tt>s</tt>. 0213 explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {} 0214 }; 0215 0216 /// \brief Input data was received that did not conform to expected format 0217 class CRYPTOPP_DLL InvalidDataFormat : public Exception 0218 { 0219 public: 0220 /// \brief Construct an InvalidDataFormat 0221 /// \param s the message for the exception 0222 /// \details The member function <tt>what()</tt> returns <tt>s</tt>. 0223 explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {} 0224 }; 0225 0226 /// \brief A decryption filter encountered invalid ciphertext 0227 class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat 0228 { 0229 public: 0230 /// \brief Construct an InvalidCiphertext 0231 /// \param s the message for the exception 0232 /// \details The member function <tt>what()</tt> returns <tt>s</tt>. 0233 explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {} 0234 }; 0235 0236 /// \brief A method was called which was not implemented 0237 class CRYPTOPP_DLL NotImplemented : public Exception 0238 { 0239 public: 0240 /// \brief Construct an NotImplemented 0241 /// \param s the message for the exception 0242 /// \details The member function <tt>what()</tt> returns <tt>s</tt>. 0243 explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {} 0244 }; 0245 0246 /// \brief Flush(true) was called but it can't completely flush its buffers 0247 class CRYPTOPP_DLL CannotFlush : public Exception 0248 { 0249 public: 0250 /// \brief Construct an CannotFlush 0251 /// \param s the message for the exception 0252 /// \details The member function <tt>what()</tt> returns <tt>s</tt>. 0253 explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {} 0254 }; 0255 0256 /// \brief The operating system reported an error 0257 class CRYPTOPP_DLL OS_Error : public Exception 0258 { 0259 public: 0260 virtual ~OS_Error() throw() {} 0261 0262 /// \brief Construct an OS_Error 0263 /// \param errorType the error type 0264 /// \param s the message for the exception 0265 /// \param operation the operation for the exception 0266 /// \param errorCode the error code 0267 /// \details The member function <tt>what()</tt> returns <tt>s</tt>. 0268 OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode) 0269 : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {} 0270 0271 /// \brief Retrieve the operating system API that reported the error 0272 const std::string & GetOperation() const {return m_operation;} 0273 /// \brief Retrieve the error code returned by the operating system 0274 int GetErrorCode() const {return m_errorCode;} 0275 0276 protected: 0277 std::string m_operation; 0278 int m_errorCode; 0279 }; 0280 0281 /// \brief Returns a decoding results 0282 struct CRYPTOPP_DLL DecodingResult 0283 { 0284 /// \brief Constructs a DecodingResult 0285 /// \details isValidCoding is initialized to false and messageLength is 0286 /// initialized to 0. 0287 explicit DecodingResult() : isValidCoding(false), messageLength(0) {} 0288 /// \brief Constructs a DecodingResult 0289 /// \param len the message length 0290 /// \details isValidCoding is initialized to true. 0291 explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {} 0292 0293 /// \brief Compare two DecodingResult 0294 /// \param rhs the other DecodingResult 0295 /// \return true if either isValidCoding or messageLength is \a not equal, 0296 /// false otherwise 0297 bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;} 0298 /// \brief Compare two DecodingResult 0299 /// \param rhs the other DecodingResult 0300 /// \return true if either isValidCoding or messageLength is \a not equal, 0301 /// false otherwise 0302 /// \details Returns <tt>!operator==(rhs)</tt>. 0303 bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);} 0304 0305 /// \brief Flag to indicate the decoding is valid 0306 bool isValidCoding; 0307 /// \brief Recovered message length if isValidCoding is true, undefined otherwise 0308 size_t messageLength; 0309 }; 0310 0311 /// \brief Interface for retrieving values given their names 0312 /// \details This class is used to safely pass a variable number of arbitrarily 0313 /// typed arguments to functions and to read values from keys and crypto parameters. 0314 /// \details To obtain an object that implements NameValuePairs for the purpose of 0315 /// parameter passing, use the MakeParameters() function. 0316 /// \details To get a value from NameValuePairs, you need to know the name and the 0317 /// type of the value. Call GetValueNames() on a NameValuePairs object to obtain a 0318 /// list of value names that it supports. then look at the Name namespace 0319 /// documentation to see what the type of each value is, or alternatively, call 0320 /// GetIntValue() with the value name, and if the type is not int, a 0321 /// ValueTypeMismatch exception will be thrown and you can get the actual type from 0322 /// the exception object. 0323 /// \sa NullNameValuePairs, g_nullNameValuePairs, 0324 /// <A HREF="http://www.cryptopp.com/wiki/NameValuePairs">NameValuePairs</A> on the 0325 /// Crypto++ wiki 0326 class NameValuePairs 0327 { 0328 public: 0329 virtual ~NameValuePairs() {} 0330 0331 /// \brief Thrown when an unexpected type is encountered 0332 /// \details Exception thrown when trying to retrieve a value using a different 0333 /// type than expected 0334 class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument 0335 { 0336 public: 0337 /// \brief Construct a ValueTypeMismatch 0338 /// \param name the name of the value 0339 /// \param stored the \a actual type of the value stored 0340 /// \param retrieving the \a presumed type of the value retrieved 0341 ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving) 0342 : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'") 0343 , m_stored(stored), m_retrieving(retrieving) {} 0344 0345 /// \brief Provides the stored type 0346 /// \return the C++ mangled name of the type 0347 const std::type_info & GetStoredTypeInfo() const {return m_stored;} 0348 0349 /// \brief Provides the retrieveing type 0350 /// \return the C++ mangled name of the type 0351 const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;} 0352 0353 private: 0354 const std::type_info &m_stored; 0355 const std::type_info &m_retrieving; 0356 }; 0357 0358 /// \brief Get a copy of this object or subobject 0359 /// \tparam T class or type 0360 /// \param object reference to a variable that receives the value 0361 template <class T> 0362 bool GetThisObject(T &object) const 0363 { 0364 return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object); 0365 } 0366 0367 /// \brief Get a pointer to this object 0368 /// \tparam T class or type 0369 /// \param ptr reference to a pointer to a variable that receives the value 0370 template <class T> 0371 bool GetThisPointer(T *&ptr) const 0372 { 0373 return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr); 0374 } 0375 0376 /// \brief Get a named value 0377 /// \tparam T class or type 0378 /// \param name the name of the object or value to retrieve 0379 /// \param value reference to a variable that receives the value 0380 /// \return true if the value was retrieved, false otherwise 0381 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0382 /// GetRequiredParameter() and GetRequiredIntParameter() 0383 template <class T> 0384 bool GetValue(const char *name, T &value) const 0385 { 0386 return GetVoidValue(name, typeid(T), &value); 0387 } 0388 0389 /// \brief Get a named value 0390 /// \tparam T class or type 0391 /// \param name the name of the object or value to retrieve 0392 /// \param defaultValue the default value of the class or type if it does not exist 0393 /// \return the object or value 0394 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0395 /// GetRequiredParameter() and GetRequiredIntParameter() 0396 template <class T> 0397 T GetValueWithDefault(const char *name, T defaultValue) const 0398 { 0399 T value; 0400 bool result = GetValue(name, value); 0401 // No assert... this recovers from failure 0402 if (result) {return value;} 0403 return defaultValue; 0404 } 0405 0406 /// \brief Get a list of value names that can be retrieved 0407 /// \return a list of names available to retrieve 0408 /// \details the items in the list are delimited with a colon. 0409 CRYPTOPP_DLL std::string GetValueNames() const 0410 {std::string result; GetValue("ValueNames", result); return result;} 0411 0412 /// \brief Get a named value with type int 0413 /// \param name the name of the value to retrieve 0414 /// \param value the value retrieved upon success 0415 /// \return true if an int value was retrieved, false otherwise 0416 /// \details GetIntValue() is used to ensure we don't accidentally try to get an 0417 /// unsigned int or some other type when we mean int (which is the most common case) 0418 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0419 /// GetRequiredParameter() and GetRequiredIntParameter() 0420 CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const 0421 {return GetValue(name, value);} 0422 0423 /// \brief Get a named value with type int, with default 0424 /// \param name the name of the value to retrieve 0425 /// \param defaultValue the default value if the name does not exist 0426 /// \return the value retrieved on success or the default value 0427 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0428 /// GetRequiredParameter() and GetRequiredIntParameter() 0429 CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const 0430 {return GetValueWithDefault(name, defaultValue);} 0431 0432 /// \brief Get a named value with type word64 0433 /// \param name the name of the value to retrieve 0434 /// \param value the value retrieved upon success 0435 /// \return true if an word64 value was retrieved, false otherwise 0436 /// \sa GetValue(), GetValueWithDefault(), GetWord64ValueWithDefault(), GetIntValue(), 0437 /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredIntParameter() 0438 CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const 0439 {return GetValue(name, value);} 0440 0441 /// \brief Get a named value with type word64, with default 0442 /// \param name the name of the value to retrieve 0443 /// \param defaultValue the default value if the name does not exist 0444 /// \return the value retrieved on success or the default value 0445 /// \sa GetValue(), GetValueWithDefault(), GetWord64Value(), GetIntValue(), 0446 /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredWord64Parameter() 0447 CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const 0448 {return GetValueWithDefault(name, defaultValue);} 0449 0450 /// \brief Ensures an expected name and type is present 0451 /// \param name the name of the value 0452 /// \param stored the type that was stored for the name 0453 /// \param retrieving the type that is being retrieved for the name 0454 /// \throw ValueTypeMismatch 0455 /// \details ThrowIfTypeMismatch() effectively performs a type safety check. 0456 /// stored and retrieving are C++ mangled names for the type. 0457 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0458 /// GetRequiredParameter() and GetRequiredIntParameter() 0459 CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving) 0460 {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);} 0461 0462 /// \brief Retrieves a required name/value pair 0463 /// \tparam T class or type 0464 /// \param className the name of the class 0465 /// \param name the name of the value 0466 /// \param value reference to a variable to receive the value 0467 /// \throw InvalidArgument 0468 /// \details GetRequiredParameter() throws InvalidArgument if the name 0469 /// is not present or not of the expected type T. 0470 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0471 /// GetRequiredParameter() and GetRequiredIntParameter() 0472 template <class T> 0473 void GetRequiredParameter(const char *className, const char *name, T &value) const 0474 { 0475 if (!GetValue(name, value)) 0476 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); 0477 } 0478 0479 /// \brief Retrieves a required name/value pair 0480 /// \param className the name of the class 0481 /// \param name the name of the value 0482 /// \param value reference to a variable to receive the value 0483 /// \throw InvalidArgument 0484 /// \details GetRequiredParameter() throws InvalidArgument if the name 0485 /// is not present or not of the expected type T. 0486 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0487 /// GetRequiredParameter() and GetRequiredIntParameter() 0488 CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const 0489 { 0490 if (!GetIntValue(name, value)) 0491 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'"); 0492 } 0493 0494 /// \brief Get a named value 0495 /// \param name the name of the object or value to retrieve 0496 /// \param valueType reference to a variable that receives the value 0497 /// \param pValue void pointer to a variable that receives the value 0498 /// \return true if the value was retrieved, false otherwise 0499 /// \details GetVoidValue() retrieves the value of name if it exists. 0500 /// \note GetVoidValue() is an internal function and should be implemented 0501 /// by derived classes. Users should use one of the other functions instead. 0502 /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(), 0503 /// GetRequiredParameter() and GetRequiredIntParameter() 0504 CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0; 0505 }; 0506 0507 // Doxygen cannot handle initialization 0508 #if CRYPTOPP_DOXYGEN_PROCESSING 0509 /// \brief Default channel for BufferedTransformation 0510 /// \details DEFAULT_CHANNEL is equal to an empty string 0511 /// \details The definition for DEFAULT_CHANNEL is in <tt>cryptlib.cpp</tt>. 0512 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static 0513 /// Initialization Order Fiasco</A>. If you experience a crash in 0514 /// DEFAULT_CHANNEL where the string object is NULL, then you probably have 0515 /// a global object using DEFAULT_CHANNEL before it has been constructed. 0516 const std::string DEFAULT_CHANNEL; 0517 0518 /// \brief Channel for additional authenticated data 0519 /// \details AAD_CHANNEL is equal to "AAD" 0520 /// \details The definition for AAD_CHANNEL is in <tt>cryptlib.cpp</tt>. 0521 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static 0522 /// Initialization Order Fiasco</A>. If you experience a crash in 0523 /// AAD_CHANNEL where the string object is NULL, then you probably have a 0524 /// global object using AAD_CHANNEL before it has been constructed. 0525 const std::string AAD_CHANNEL; 0526 0527 /// \brief An empty set of name-value pairs 0528 /// \details The definition for g_nullNameValuePairs is in <tt>cryptlib.cpp</tt>. 0529 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static 0530 /// Initialization Order Fiasco</A>. If you experience a crash in 0531 /// g_nullNameValuePairs where the string object is NULL, then you probably 0532 /// have a global object using g_nullNameValuePairs before it has been 0533 /// constructed. 0534 const NameValuePairs& g_nullNameValuePairs; 0535 0536 #else 0537 extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL; 0538 extern CRYPTOPP_DLL const std::string AAD_CHANNEL; 0539 extern CRYPTOPP_DLL const NameValuePairs& g_nullNameValuePairs; 0540 #endif 0541 0542 // Document additional name spaces which show up elsewhere in the sources. 0543 #if CRYPTOPP_DOXYGEN_PROCESSING 0544 /// \brief Namespace containing value name definitions. 0545 /// \details Name is part of the CryptoPP namespace. 0546 /// \details The semantics of value names, types are: 0547 /// <pre> 0548 /// ThisObject:ClassName (ClassName, copy of this object or a subobject) 0549 /// ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject) 0550 /// </pre> 0551 DOCUMENTED_NAMESPACE_BEGIN(Name) 0552 // more names defined in argnames.h 0553 DOCUMENTED_NAMESPACE_END 0554 0555 /// \brief Namespace containing weak and wounded algorithms. 0556 /// \details Weak is part of the CryptoPP namespace. Schemes and algorithms are moved into Weak 0557 /// when their security level is reduced to an unacceptable level by contemporary standards. 0558 /// \details To use an algorithm in the Weak namespace, you must <tt>\c \#define 0559 /// CRYPTOPP_ENABLE_NAMESPACE_WEAK 1</tt> before including a header for a weak or wounded 0560 /// algorithm. For example: 0561 /// <pre> \c \#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 0562 /// \c \#include <md5.h> 0563 /// ... 0564 /// CryptoPP::Weak::MD5 md5; 0565 /// </pre> 0566 DOCUMENTED_NAMESPACE_BEGIN(Weak) 0567 // weak and wounded algorithms 0568 DOCUMENTED_NAMESPACE_END 0569 #endif 0570 0571 /// \brief Namespace containing NaCl library functions 0572 /// \details TweetNaCl is a compact and portable reimplementation of the NaCl library. 0573 DOCUMENTED_NAMESPACE_BEGIN(NaCl) 0574 // crypto_box, crypto_box_open, crypto_sign, and crypto_sign_open (and friends) 0575 DOCUMENTED_NAMESPACE_END 0576 0577 /// \brief Namespace containing testing and benchmark classes. 0578 /// \details Source files for classes in the Test namespaces include 0579 /// <tt>test.cpp</tt>, <tt>validat#.cpp</tt> and <tt>bench#.cpp</tt>. 0580 DOCUMENTED_NAMESPACE_BEGIN(Test) 0581 // testing and benchmark classes 0582 DOCUMENTED_NAMESPACE_END 0583 0584 // ******************************************************** 0585 0586 /// \brief Interface for cloning objects 0587 /// \note this is \a not implemented by most classes 0588 /// \sa ClonableImpl, NotCopyable 0589 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable 0590 { 0591 public: 0592 virtual ~Clonable() {} 0593 0594 /// \brief Copies this object 0595 /// \return a copy of this object 0596 /// \throw NotImplemented 0597 /// \note this is \a not implemented by most classes 0598 /// \sa NotCopyable 0599 virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0 0600 }; 0601 0602 /// \brief Interface for all crypto algorithms 0603 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable 0604 { 0605 public: 0606 virtual ~Algorithm() {} 0607 0608 /// \brief Interface for all crypto algorithms 0609 /// \param checkSelfTestStatus determines whether the object can proceed if the self 0610 /// tests have not been run or failed. 0611 /// \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true, 0612 /// this constructor throws SelfTestFailure if the self test hasn't been run or fails. 0613 /// \details FIPS 140-2 compliance is disabled by default. It is only used by certain 0614 /// versions of the library when the library is built as a DLL on Windows. Also see 0615 /// CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h. 0616 Algorithm(bool checkSelfTestStatus = true); 0617 0618 /// \brief Provides the name of this algorithm 0619 /// \return the standard algorithm name 0620 /// \details The standard algorithm name can be a name like <tt>AES</tt> or <tt>AES/GCM</tt>. 0621 /// Some algorithms do not have standard names yet. For example, there is no standard 0622 /// algorithm name for Shoup's ECIES. 0623 /// \note AlgorithmName is not universally implemented yet. 0624 virtual std::string AlgorithmName() const {return "unknown";} 0625 0626 /// \brief Retrieve the provider of this algorithm 0627 /// \return the algorithm provider 0628 /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI", 0629 /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE, 0630 /// usually indicate a specialized implementation using instructions from a higher 0631 /// instruction set architecture (ISA). Future labels may include external hardware 0632 /// like a hardware security module (HSM). 0633 /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2". 0634 /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics 0635 /// instead of ASM. 0636 /// \details Algorithms which combine different instructions or ISAs provide the 0637 /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than 0638 /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL". 0639 /// \note Provider is not universally implemented yet. 0640 /// \since Crypto++ 8.0 0641 virtual std::string AlgorithmProvider() const {return "C++";} 0642 }; 0643 0644 /// \brief Interface for algorithms that take byte strings as keys 0645 /// \sa FixedKeyLength(), VariableKeyLength(), SameKeyLengthAs(), SimpleKeyingInterfaceImpl() 0646 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface 0647 { 0648 public: 0649 virtual ~SimpleKeyingInterface() {} 0650 0651 /// \brief Returns smallest valid key length 0652 /// \return the minimum key length, in bytes 0653 virtual size_t MinKeyLength() const =0; 0654 0655 /// \brief Returns largest valid key length 0656 /// \return the maximum key length, in bytes 0657 virtual size_t MaxKeyLength() const =0; 0658 0659 /// \brief Returns default key length 0660 /// \return the default key length, in bytes 0661 virtual size_t DefaultKeyLength() const =0; 0662 0663 /// \brief Returns a valid key length for the algorithm 0664 /// \param keylength the size of the key, in bytes 0665 /// \return the valid key length, in bytes 0666 /// \details keylength is provided in bytes, not bits. If keylength is less than MIN_KEYLENGTH, 0667 /// then the function returns MIN_KEYLENGTH. If keylength is greater than MAX_KEYLENGTH, 0668 /// then the function returns MAX_KEYLENGTH. if If keylength is a multiple of KEYLENGTH_MULTIPLE, 0669 /// then keylength is returned. Otherwise, the function returns a \a lower multiple of 0670 /// KEYLENGTH_MULTIPLE. 0671 virtual size_t GetValidKeyLength(size_t keylength) const =0; 0672 0673 /// \brief Returns whether keylength is a valid key length 0674 /// \param keylength the requested keylength 0675 /// \return true if keylength is valid, false otherwise 0676 /// \details Internally the function calls GetValidKeyLength() 0677 virtual bool IsValidKeyLength(size_t keylength) const 0678 {return keylength == GetValidKeyLength(keylength);} 0679 0680 /// \brief Sets or reset the key of this object 0681 /// \param key the key to use when keying the object 0682 /// \param length the size of the key, in bytes 0683 /// \param params additional initialization parameters to configure this object 0684 virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms = g_nullNameValuePairs); 0685 0686 /// \brief Sets or reset the key of this object 0687 /// \param key the key to use when keying the object 0688 /// \param length the size of the key, in bytes 0689 /// \param rounds the number of rounds to apply the transformation function, 0690 /// if applicable 0691 /// \details SetKeyWithRounds() calls SetKey() with a NameValuePairs 0692 /// object that only specifies rounds. rounds is an integer parameter, 0693 /// and <tt>-1</tt> means use the default number of rounds. 0694 void SetKeyWithRounds(const byte *key, size_t length, int rounds); 0695 0696 /// \brief Sets or reset the key of this object 0697 /// \param key the key to use when keying the object 0698 /// \param length the size of the key, in bytes 0699 /// \param iv the initialization vector to use when keying the object 0700 /// \param ivLength the size of the iv, in bytes 0701 /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs 0702 /// that only specifies IV. The IV is a byte buffer with size ivLength. 0703 /// ivLength is an integer parameter, and <tt>-1</tt> means use IVSize(). 0704 void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength); 0705 0706 /// \brief Sets or reset the key of this object 0707 /// \param key the key to use when keying the object 0708 /// \param length the size of the key, in bytes 0709 /// \param iv the initialization vector to use when keying the object 0710 /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs() object 0711 /// that only specifies iv. iv is a byte buffer, and it must have 0712 /// a size IVSize(). 0713 void SetKeyWithIV(const byte *key, size_t length, const byte *iv) 0714 {SetKeyWithIV(key, length, iv, IVSize());} 0715 0716 /// \brief Secure IVs requirements as enumerated values. 0717 /// \details Provides secure IV requirements as a monotonically increasing enumerated values. 0718 /// Requirements can be compared using less than (<) and greater than (>). For example, 0719 /// <tt>UNIQUE_IV < RANDOM_IV</tt> and <tt>UNPREDICTABLE_RANDOM_IV > RANDOM_IV</tt>. 0720 /// \details Objects that use SimpleKeyingInterface do not support an optional IV. That is, 0721 /// an IV must be present or it must be absent. If you wish to support an optional IV then 0722 /// provide two classes - one with an IV and one without an IV. 0723 /// \sa IsResynchronizable(), CanUseRandomIVs(), CanUsePredictableIVs(), CanUseStructuredIVs() 0724 enum IV_Requirement { 0725 /// \brief The IV must be unique 0726 UNIQUE_IV = 0, 0727 /// \brief The IV must be random and possibly predictable 0728 RANDOM_IV, 0729 /// \brief The IV must be random and unpredictable 0730 UNPREDICTABLE_RANDOM_IV, 0731 /// \brief The IV is set by the object 0732 INTERNALLY_GENERATED_IV, 0733 /// \brief The object does not use an IV 0734 NOT_RESYNCHRONIZABLE 0735 }; 0736 0737 /// \brief Minimal requirement for secure IVs 0738 /// \return the secure IV requirement of the algorithm 0739 virtual IV_Requirement IVRequirement() const =0; 0740 0741 /// \brief Determines if the object can be resynchronized 0742 /// \return true if the object can be resynchronized (i.e. supports initialization vectors), false otherwise 0743 /// \note If this function returns true, and no IV is passed to SetKey() and <tt>CanUseStructuredIVs()==true</tt>, 0744 /// an IV of all 0's will be assumed. 0745 bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;} 0746 0747 /// \brief Determines if the object can use random IVs 0748 /// \return true if the object can use random IVs (in addition to ones returned by GetNextIV), false otherwise 0749 bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;} 0750 0751 /// \brief Determines if the object can use random but possibly predictable IVs 0752 /// \return true if the object can use random but possibly predictable IVs (in addition to ones returned by 0753 /// GetNextIV), false otherwise 0754 bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;} 0755 0756 /// \brief Determines if the object can use structured IVs 0757 /// \return true if the object can use structured IVs, false otherwise 0758 /// \details CanUseStructuredIVs() indicates whether the object can use structured IVs; for example a counter 0759 /// (in addition to ones returned by GetNextIV). 0760 bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;} 0761 0762 /// \brief Returns length of the IV accepted by this object 0763 /// \return the size of an IV, in bytes 0764 /// \throw NotImplemented() if the object does not support resynchronization 0765 /// \details The default implementation throws NotImplemented 0766 virtual unsigned int IVSize() const 0767 {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");} 0768 0769 /// \brief Provides the default size of an IV 0770 /// \return default length of IVs accepted by this object, in bytes 0771 unsigned int DefaultIVLength() const {return IVSize();} 0772 0773 /// \brief Provides the minimum size of an IV 0774 /// \return minimal length of IVs accepted by this object, in bytes 0775 /// \throw NotImplemented() if the object does not support resynchronization 0776 virtual unsigned int MinIVLength() const {return IVSize();} 0777 0778 /// \brief Provides the maximum size of an IV 0779 /// \return maximal length of IVs accepted by this object, in bytes 0780 /// \throw NotImplemented() if the object does not support resynchronization 0781 virtual unsigned int MaxIVLength() const {return IVSize();} 0782 0783 /// \brief Resynchronize with an IV 0784 /// \param iv the initialization vector 0785 /// \param ivLength the size of the initialization vector, in bytes 0786 /// \details Resynchronize() resynchronizes with an IV provided by the caller. <tt>ivLength=-1</tt> means use IVSize(). 0787 /// \throw NotImplemented() if the object does not support resynchronization 0788 virtual void Resynchronize(const byte *iv, int ivLength=-1) { 0789 CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength); 0790 throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization"); 0791 } 0792 0793 /// \brief Retrieves a secure IV for the next message 0794 /// \param rng a RandomNumberGenerator to produce keying material 0795 /// \param iv a block of bytes to receive the IV 0796 /// \details The IV must be at least IVSize() in length. 0797 /// \details This method should be called after you finish encrypting one message and are ready 0798 /// to start the next one. After calling it, you must call SetKey() or Resynchronize(). 0799 /// before using this object again. 0800 /// \details Internally, the base class implementation calls RandomNumberGenerator's GenerateBlock() 0801 /// \note This method is not implemented on decryption objects. 0802 virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv); 0803 0804 protected: 0805 /// \brief Returns the base class Algorithm 0806 /// \return the base class Algorithm 0807 virtual const Algorithm & GetAlgorithm() const =0; 0808 0809 /// \brief Sets the key for this object without performing parameter validation 0810 /// \param key a byte buffer used to key the cipher 0811 /// \param length the length of the byte buffer 0812 /// \param params additional parameters passed as NameValuePairs 0813 /// \details key must be at least DEFAULT_KEYLENGTH in length. 0814 virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms) =0; 0815 0816 /// \brief Validates the key length 0817 /// \param length the size of the keying material, in bytes 0818 /// \throw InvalidKeyLength if the key length is invalid 0819 void ThrowIfInvalidKeyLength(size_t length); 0820 0821 /// \brief Validates the object 0822 /// \throw InvalidArgument if the IV is present 0823 /// \details Internally, the default implementation calls IsResynchronizable() and throws 0824 /// InvalidArgument if the function returns true. 0825 /// \note called when no IV is passed 0826 void ThrowIfResynchronizable(); 0827 0828 /// \brief Validates the IV 0829 /// \param iv the IV with a length of IVSize, in bytes 0830 /// \throw InvalidArgument on failure 0831 /// \details Internally, the default implementation checks the iv. If iv is not NULL or nullptr, 0832 /// then the function succeeds. If iv is NULL, then IVRequirement is checked against 0833 /// UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then 0834 /// then the function succeeds. Otherwise, an exception is thrown. 0835 void ThrowIfInvalidIV(const byte *iv); 0836 0837 /// \brief Validates the IV length 0838 /// \param length the size of an IV, in bytes 0839 /// \throw InvalidArgument if the IV length is invalid 0840 size_t ThrowIfInvalidIVLength(int length); 0841 0842 /// \brief Retrieves and validates the IV 0843 /// \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter 0844 /// \param size the length of the IV, in bytes 0845 /// \return a pointer to the first byte of the IV 0846 /// \throw InvalidArgument if the number of rounds are invalid 0847 const byte * GetIVAndThrowIfInvalid(const NameValuePairs ¶ms, size_t &size); 0848 0849 /// \brief Validates the key length 0850 /// \param length the size of the keying material, in bytes 0851 inline void AssertValidKeyLength(size_t length) const 0852 {CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));} 0853 }; 0854 0855 /// \brief Interface for the data processing part of block ciphers 0856 /// \details Classes derived from BlockTransformation are block ciphers 0857 /// in ECB mode (for example the DES::Encryption class), which are stateless. 0858 /// These classes should not be used directly, but only in combination with 0859 /// a mode class (see CipherModeDocumentation in modes.h). 0860 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm 0861 { 0862 public: 0863 virtual ~BlockTransformation() {} 0864 0865 /// \brief Encrypt or decrypt a block 0866 /// \param inBlock the input message before processing 0867 /// \param outBlock the output message after processing 0868 /// \param xorBlock an optional XOR mask 0869 /// \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock. 0870 /// \details The size of the block is determined by the block cipher and its documentation. Use 0871 /// BLOCKSIZE at compile time, or BlockSize() at runtime. 0872 /// \note The message can be transformed in-place, or the buffers must \a not overlap 0873 /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize() 0874 virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0; 0875 0876 /// \brief Encrypt or decrypt a block 0877 /// \param inBlock the input message before processing 0878 /// \param outBlock the output message after processing 0879 /// \details ProcessBlock encrypts or decrypts inBlock and write to outBlock. 0880 /// \details The size of the block is determined by the block cipher and its documentation. 0881 /// Use BLOCKSIZE at compile time, or BlockSize() at runtime. 0882 /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize() 0883 /// \note The message can be transformed in-place, or the buffers must \a not overlap 0884 void ProcessBlock(const byte *inBlock, byte *outBlock) const 0885 {ProcessAndXorBlock(inBlock, NULLPTR, outBlock);} 0886 0887 /// \brief Encrypt or decrypt a block in place 0888 /// \param inoutBlock the input message before processing 0889 /// \details ProcessBlock encrypts or decrypts inoutBlock in-place. 0890 /// \details The size of the block is determined by the block cipher and its documentation. 0891 /// Use BLOCKSIZE at compile time, or BlockSize() at runtime. 0892 /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize() 0893 void ProcessBlock(byte *inoutBlock) const 0894 {ProcessAndXorBlock(inoutBlock, NULLPTR, inoutBlock);} 0895 0896 /// Provides the block size of the cipher 0897 /// \return the block size of the cipher, in bytes 0898 virtual unsigned int BlockSize() const =0; 0899 0900 /// \brief Provides input and output data alignment for optimal performance. 0901 /// \return the input data alignment that provides optimal performance 0902 /// \sa GetAlignment() and OptimalBlockSize() 0903 virtual unsigned int OptimalDataAlignment() const; 0904 0905 /// \brief Determines if the transformation is a permutation 0906 /// \return true if this is a permutation (i.e. there is an inverse transformation) 0907 virtual bool IsPermutation() const {return true;} 0908 0909 /// \brief Determines if the cipher is being operated in its forward direction 0910 /// \return true if DIR is ENCRYPTION, false otherwise 0911 /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection() 0912 virtual bool IsForwardTransformation() const =0; 0913 0914 /// \brief Determines the number of blocks that can be processed in parallel 0915 /// \return the number of blocks that can be processed in parallel, for bit-slicing implementations 0916 /// \details Bit-slicing is often used to improve throughput and minimize timing attacks. 0917 virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;} 0918 0919 /// \brief Bit flags that control AdvancedProcessBlocks() behavior 0920 enum FlagsForAdvancedProcessBlocks { 0921 /// \brief inBlock is a counter 0922 BT_InBlockIsCounter=1, 0923 /// \brief should not modify block pointers 0924 BT_DontIncrementInOutPointers=2, 0925 /// \brief Xor inputs before transformation 0926 BT_XorInput=4, 0927 /// \brief perform the transformation in reverse 0928 BT_ReverseDirection=8, 0929 /// \brief Allow parallel transformations 0930 BT_AllowParallel=16}; 0931 0932 /// \brief Encrypt and xor multiple blocks using additional flags 0933 /// \param inBlocks the input message before processing 0934 /// \param xorBlocks an optional XOR mask 0935 /// \param outBlocks the output message after processing 0936 /// \param length the size of the blocks, in bytes 0937 /// \param flags additional flags to control processing 0938 /// \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags. 0939 /// \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified. 0940 virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const; 0941 0942 /// \brief Provides the direction of the cipher 0943 /// \return ENCRYPTION if IsForwardTransformation() is true, DECRYPTION otherwise 0944 /// \sa IsForwardTransformation(), IsPermutation() 0945 inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;} 0946 }; 0947 0948 /// \brief Interface for the data processing portion of stream ciphers 0949 /// \sa StreamTransformationFilter() 0950 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm 0951 { 0952 public: 0953 virtual ~StreamTransformation() {} 0954 0955 /// \brief Provides a reference to this object 0956 /// \return A reference to this object 0957 /// \details Useful for passing a temporary object to a function that takes a non-const reference 0958 StreamTransformation& Ref() {return *this;} 0959 0960 /// \brief Provides the mandatory block size of the cipher 0961 /// \return The block size of the cipher if input must be processed in blocks, 1 otherwise 0962 /// \details Stream ciphers and some block ciphers modes of operation return 1. Modes that 0963 /// return 1 must be able to process a single byte at a time, like counter mode. If a 0964 /// mode of operation or block cipher cannot stream then it must not return 1. 0965 /// \details When filters operate the mode or cipher, ProcessData will be called with a 0966 /// string of bytes that is determined by MandatoryBlockSize and OptimalBlockSize. When a 0967 /// policy is set, like 16-byte strings for a 16-byte block cipher, the filter will buffer 0968 /// bytes until the specified number of bytes is available to the object. 0969 /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial 0970 virtual unsigned int MandatoryBlockSize() const {return 1;} 0971 0972 /// \brief Provides the input block size most efficient for this cipher 0973 /// \return The input block size that is most efficient for the cipher 0974 /// \details The base class implementation returns MandatoryBlockSize(). 0975 /// \note Optimal input length is 0976 /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>. 0977 virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();} 0978 0979 /// \brief Provides the number of bytes used in the current block when processing at optimal block size. 0980 /// \return the number of bytes used in the current block when processing at the optimal block size 0981 virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;} 0982 0983 /// \brief Provides input and output data alignment for optimal performance 0984 /// \return the input data alignment that provides optimal performance 0985 /// \sa GetAlignment() and OptimalBlockSize() 0986 virtual unsigned int OptimalDataAlignment() const; 0987 0988 /// \brief Encrypt or decrypt an array of bytes 0989 /// \param outString the output byte buffer 0990 /// \param inString the input byte buffer 0991 /// \param length the size of the input and output byte buffers, in bytes 0992 /// \details ProcessData is called with a string of bytes whose size depends on MandatoryBlockSize. 0993 /// Either <tt>inString == outString</tt>, or they must not overlap. 0994 /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial 0995 virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0; 0996 0997 /// \brief Encrypt or decrypt the last block of data 0998 /// \param outString the output byte buffer 0999 /// \param outLength the size of the output byte buffer, in bytes 1000 /// \param inString the input byte buffer 1001 /// \param inLength the size of the input byte buffer, in bytes 1002 /// \return the number of bytes used in outString 1003 /// \details ProcessLastBlock is used when the last block of data is special and requires handling 1004 /// by the cipher. The current implementation provides an output buffer with a size 1005 /// <tt>inLength+2*MandatoryBlockSize()</tt>. The return value allows the cipher to expand cipher 1006 /// text during encryption or shrink plain text during decryption. 1007 /// \details This member function is used by CBC-CTS and OCB modes. 1008 /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial 1009 virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength); 1010 1011 /// \brief Provides the size of the last block 1012 /// \return the minimum size of the last block 1013 /// \details MinLastBlockSize() returns the minimum size of the last block. 0 indicates the last 1014 /// block is not special. 1015 /// \details MandatoryBlockSize() enlists one of two behaviors. First, if MandatoryBlockSize() 1016 /// returns 1, then the cipher can be streamed and ProcessData() is called with the tail bytes. 1017 /// Second, if MandatoryBlockSize() returns non-0, then the string of bytes is padded to 1018 /// MandatoryBlockSize() according to the padding mode. Then, ProcessData() is called with the 1019 /// padded string of bytes. 1020 /// \details Some authenticated encryption modes are not expressed well with MandatoryBlockSize() 1021 /// and MinLastBlockSize(). For example, AES/OCB uses 16-byte blocks (MandatoryBlockSize = 16) 1022 /// and the last block requires special processing (MinLastBlockSize = 0). However, 0 is a valid 1023 /// last block size for OCB and the special processing is custom padding, and not standard PKCS 1024 /// padding. In response an unambiguous IsLastBlockSpecial() was added. 1025 /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial 1026 virtual unsigned int MinLastBlockSize() const {return 0;} 1027 1028 /// \brief Determines if the last block receives special processing 1029 /// \return true if the last block receives special processing, false otherwise. 1030 /// \details Some authenticated encryption modes are not expressed well with 1031 /// MandatoryBlockSize() and MinLastBlockSize(). For example, AES/OCB uses 1032 /// 16-byte blocks (MandatoryBlockSize = 16) and the last block requires special processing 1033 /// (MinLastBlockSize = 0). However, 0 is a valid last block size for OCB and the special 1034 /// processing is custom padding, and not standard PKCS padding. In response an 1035 /// unambiguous IsLastBlockSpecial() was added. 1036 /// \details When IsLastBlockSpecial() returns false nothing special happens. All the former 1037 /// rules and behaviors apply. This is the default behavior of IsLastBlockSpecial(). 1038 /// \details When IsLastBlockSpecial() returns true four things happen. First, MinLastBlockSize = 0 1039 /// means 0 is a valid block size that should be processed. Second, standard block cipher padding is 1040 /// \a not \a applied. Third, the caller supplies an outString is larger than inString by 1041 /// <tt>2*MandatoryBlockSize()</tt>. That is, there's a reserve available when processing the last block. 1042 /// Fourth, the cipher is responsible for finalization like custom padding. The cipher will tell 1043 /// the library how many bytes were processed or used by returning the appropriate value from 1044 /// ProcessLastBlock(). 1045 /// \details The return value of ProcessLastBlock() indicates how many bytes were written to 1046 /// <tt>outString</tt>. A filter pipelining data will send <tt>outString</tt> and up to <tt>outLength</tt> 1047 /// to an <tt>AttachedTransformation()</tt> for additional processing. Below is an example of the code 1048 /// used in <tt>StreamTransformationFilter::LastPut</tt>. 1049 /// <pre> if (m_cipher.IsLastBlockSpecial()) 1050 /// { 1051 /// size_t reserve = 2*m_cipher.MandatoryBlockSize(); 1052 /// space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, length+reserve); 1053 /// length = m_cipher.ProcessLastBlock(space, length+reserve, inString, length); 1054 /// AttachedTransformation()->Put(space, length); 1055 /// return; 1056 /// }</pre> 1057 /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial 1058 /// \since Crypto++ 6.0 1059 virtual bool IsLastBlockSpecial() const {return false;} 1060 1061 /// \brief Encrypt or decrypt a string of bytes 1062 /// \param inoutString the string to process 1063 /// \param length the size of the inoutString, in bytes 1064 /// \details Internally, the base class implementation calls ProcessData(). 1065 inline void ProcessString(byte *inoutString, size_t length) 1066 {ProcessData(inoutString, inoutString, length);} 1067 1068 /// \brief Encrypt or decrypt a string of bytes 1069 /// \param outString the output string to process 1070 /// \param inString the input string to process 1071 /// \param length the size of the input and output strings, in bytes 1072 /// \details Internally, the base class implementation calls ProcessData(). 1073 inline void ProcessString(byte *outString, const byte *inString, size_t length) 1074 {ProcessData(outString, inString, length);} 1075 1076 /// \brief Encrypt or decrypt a byte 1077 /// \param input the input byte to process 1078 /// \details Internally, the base class implementation calls ProcessData() with a size of 1. 1079 inline byte ProcessByte(byte input) 1080 {ProcessData(&input, &input, 1); return input;} 1081 1082 /// \brief Determines whether the cipher supports random access 1083 /// \return true if the cipher supports random access, false otherwise 1084 virtual bool IsRandomAccess() const =0; 1085 1086 /// \brief Seek to an absolute position 1087 /// \param pos position to seek 1088 /// \throw NotImplemented 1089 /// \details The base class implementation throws NotImplemented. The function 1090 /// \ref CRYPTOPP_ASSERT "asserts" IsRandomAccess() in debug builds. 1091 virtual void Seek(lword pos) 1092 { 1093 CRYPTOPP_UNUSED(pos); 1094 CRYPTOPP_ASSERT(!IsRandomAccess()); 1095 throw NotImplemented("StreamTransformation: this object doesn't support random access"); 1096 } 1097 1098 /// \brief Determines whether the cipher is self-inverting 1099 /// \return true if the cipher is self-inverting, false otherwise 1100 /// \details IsSelfInverting determines whether this transformation is 1101 /// self-inverting (e.g. xor with a keystream). 1102 virtual bool IsSelfInverting() const =0; 1103 1104 /// \brief Determines if the cipher is being operated in its forward direction 1105 /// \return true if DIR is ENCRYPTION, false otherwise 1106 /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection() 1107 virtual bool IsForwardTransformation() const =0; 1108 }; 1109 1110 /// \brief Interface for hash functions and data processing part of MACs 1111 /// \details HashTransformation objects are stateful. They are created in an initial state, 1112 /// change state as Update() is called, and return to the initial 1113 /// state when Final() is called. This interface allows a large message to 1114 /// be hashed in pieces by calling Update() on each piece followed by 1115 /// calling Final(). 1116 /// \sa HashFilter(), HashVerificationFilter() 1117 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm 1118 { 1119 public: 1120 virtual ~HashTransformation() {} 1121 1122 /// \brief Provides a reference to this object 1123 /// \return A reference to this object 1124 /// \details Useful for passing a temporary object to a function that takes a non-const reference 1125 HashTransformation& Ref() {return *this;} 1126 1127 /// \brief Updates a hash with additional input 1128 /// \param input the additional input as a buffer 1129 /// \param length the size of the buffer, in bytes 1130 virtual void Update(const byte *input, size_t length) =0; 1131 1132 /// \brief Request space which can be written into by the caller 1133 /// \param size the requested size of the buffer 1134 /// \details The purpose of this method is to help avoid extra memory allocations. 1135 /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made, 1136 /// size is the requested size of the buffer. When the call returns, size is the size of 1137 /// the array returned to the caller. 1138 /// \details The base class implementation sets size to 0 and returns NULL or nullptr. 1139 /// \note Some objects, like ArraySink, cannot create a space because its fixed. 1140 virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULLPTR;} 1141 1142 /// \brief Computes the hash of the current message 1143 /// \param digest a pointer to the buffer to receive the hash 1144 /// \details Final() restarts the hash for a new message. 1145 /// \pre <tt>COUNTOF(digest) <= DigestSize()</tt> or <tt>COUNTOF(digest) <= HASH::DIGESTSIZE</tt> ensures 1146 /// the output byte buffer is large enough for the digest. 1147 virtual void Final(byte *digest) 1148 {TruncatedFinal(digest, DigestSize());} 1149 1150 /// \brief Restart the hash 1151 /// \details Discards the current state, and restart for a new message 1152 virtual void Restart() 1153 {TruncatedFinal(NULLPTR, 0);} 1154 1155 /// Provides the digest size of the hash 1156 /// \return the digest size of the hash. 1157 virtual unsigned int DigestSize() const =0; 1158 1159 /// Provides the tag size of the hash 1160 /// \return the tag size of the hash. 1161 /// \details Same as DigestSize(). 1162 unsigned int TagSize() const {return DigestSize();} 1163 1164 /// \brief Provides the block size of the compression function 1165 /// \return block size of the compression function, in bytes 1166 /// \details BlockSize() will return 0 if the hash is not block based 1167 /// or does not have an equivalent block size. For example, Keccak 1168 /// and SHA-3 do not have a block size, but they do have an equivalent 1169 /// block size called rate expressed as <tt>r</tt>. 1170 virtual unsigned int BlockSize() const {return 0;} 1171 1172 /// \brief Provides the input block size most efficient for this hash. 1173 /// \return The input block size that is most efficient for the cipher 1174 /// \details The base class implementation returns MandatoryBlockSize(). 1175 /// \details Optimal input length is 1176 /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>. 1177 virtual unsigned int OptimalBlockSize() const {return 1;} 1178 1179 /// \brief Provides input and output data alignment for optimal performance 1180 /// \return the input data alignment that provides optimal performance 1181 /// \sa GetAlignment() and OptimalBlockSize() 1182 virtual unsigned int OptimalDataAlignment() const; 1183 1184 /// \brief Updates the hash with additional input and computes the hash of the current message 1185 /// \param digest a pointer to the buffer to receive the hash 1186 /// \param input the additional input as a buffer 1187 /// \param length the size of the buffer, in bytes 1188 /// \details Use this if your input is in one piece and you don't want to call Update() 1189 /// and Final() separately 1190 /// \details CalculateDigest() restarts the hash for the next message. 1191 /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures 1192 /// the output byte buffer is a valid size. 1193 virtual void CalculateDigest(byte *digest, const byte *input, size_t length) 1194 {Update(input, length); Final(digest);} 1195 1196 /// \brief Verifies the hash of the current message 1197 /// \param digest a pointer to the buffer of an \a existing hash 1198 /// \return \p true if the existing hash matches the computed hash, \p false otherwise 1199 /// \throw InvalidArgument() if the existing hash's size exceeds DigestSize() 1200 /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is 1201 /// a constant time comparison function. digestLength cannot exceed DigestSize(). 1202 /// \details Verify() restarts the hash for the next message. 1203 /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures 1204 /// the input byte buffer is a valid size. 1205 virtual bool Verify(const byte *digest) 1206 {return TruncatedVerify(digest, DigestSize());} 1207 1208 /// \brief Updates the hash with additional input and verifies the hash of the current message 1209 /// \param digest a pointer to the buffer of an \a existing hash 1210 /// \param input the additional input as a buffer 1211 /// \param length the size of the buffer, in bytes 1212 /// \return \p true if the existing hash matches the computed hash, \p false otherwise 1213 /// \throw InvalidArgument() if the existing hash's size exceeds DigestSize() 1214 /// \details Use this if your input is in one piece and you don't want to call Update() 1215 /// and Verify() separately 1216 /// \details VerifyDigest() performs a bitwise compare on the buffers using VerifyBufsEqual(), 1217 /// which is a constant time comparison function. 1218 /// \details VerifyDigest() restarts the hash for the next message. 1219 /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures 1220 /// the output byte buffer is a valid size. 1221 virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length) 1222 {Update(input, length); return Verify(digest);} 1223 1224 /// \brief Computes the hash of the current message 1225 /// \param digest a pointer to the buffer to receive the hash 1226 /// \param digestSize the size of the truncated digest, in bytes 1227 /// \details TruncatedFinal() calls Final() and then copies digestSize bytes to digest. 1228 /// The hash is restarted the hash for the next message. 1229 /// \pre <tt>COUNTOF(digest) <= DigestSize()</tt> or <tt>COUNTOF(digest) <= HASH::DIGESTSIZE</tt> ensures 1230 /// the output byte buffer is a valid size. 1231 virtual void TruncatedFinal(byte *digest, size_t digestSize) =0; 1232 1233 /// \brief Updates the hash with additional input and computes the hash of the current message 1234 /// \param digest a pointer to the buffer to receive the hash 1235 /// \param digestSize the length of the truncated hash, in bytes 1236 /// \param input the additional input as a buffer 1237 /// \param length the size of the buffer, in bytes 1238 /// \details Use this if your input is in one piece and you don't want to call Update() 1239 /// and CalculateDigest() separately. 1240 /// \details CalculateTruncatedDigest() restarts the hash for the next message. 1241 /// \pre <tt>digestSize <= DigestSize()</tt> or <tt>digestSize <= HASH::DIGESTSIZE</tt> ensures 1242 /// the output byte buffer is a valid size. 1243 virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length) 1244 {Update(input, length); TruncatedFinal(digest, digestSize);} 1245 1246 /// \brief Verifies the hash of the current message 1247 /// \param digest a pointer to the buffer of an \a existing hash 1248 /// \param digestLength the size of the truncated hash, in bytes 1249 /// \return \p true if the existing hash matches the computed hash, \p false otherwise 1250 /// \throw InvalidArgument() if digestLength exceeds DigestSize() 1251 /// \details TruncatedVerify() is a truncated version of Verify(). It can operate on a 1252 /// buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize(). 1253 /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is 1254 /// a constant time comparison function. digestLength cannot exceed DigestSize(). 1255 /// \details TruncatedVerify() restarts the hash for the next message. 1256 /// \pre <tt>digestLength <= DigestSize()</tt> or <tt>digestLength <= HASH::DIGESTSIZE</tt> ensures 1257 /// the input byte buffer is a valid size. 1258 virtual bool TruncatedVerify(const byte *digest, size_t digestLength); 1259 1260 /// \brief Updates the hash with additional input and verifies the hash of the current message 1261 /// \param digest a pointer to the buffer of an \a existing hash 1262 /// \param digestLength the size of the truncated hash, in bytes 1263 /// \param input the additional input as a buffer 1264 /// \param length the size of the buffer, in bytes 1265 /// \return \p true if the existing hash matches the computed hash, \p false otherwise 1266 /// \throw InvalidArgument() if digestLength exceeds DigestSize() 1267 /// \details Use this if your input is in one piece and you don't want to call Update() 1268 /// and TruncatedVerify() separately. 1269 /// \details VerifyTruncatedDigest() is a truncated version of VerifyDigest(). It can operate 1270 /// on a buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize(). 1271 /// \details VerifyTruncatedDigest() restarts the hash for the next message. 1272 /// \pre <tt>digestLength <= DigestSize()</tt> or <tt>digestLength <= HASH::DIGESTSIZE</tt> ensures 1273 /// the input byte buffer is a valid size. 1274 virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length) 1275 {Update(input, length); return TruncatedVerify(digest, digestLength);} 1276 1277 protected: 1278 /// \brief Validates a truncated digest size 1279 /// \param size the requested digest size 1280 /// \throw InvalidArgument if the algorithm's digest size cannot be truncated to the requested size 1281 /// \details Throws an exception when the truncated digest size is greater than DigestSize() 1282 void ThrowIfInvalidTruncatedSize(size_t size) const; 1283 }; 1284 1285 /// \brief Interface for one direction (encryption or decryption) of a block cipher 1286 /// \details These objects usually should not be used directly. See BlockTransformation for more details. 1287 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation 1288 { 1289 protected: 1290 const Algorithm & GetAlgorithm() const {return *this;} 1291 }; 1292 1293 /// \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode 1294 /// \details These objects usually should not be used directly. See StreamTransformation for more details. 1295 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation 1296 { 1297 protected: 1298 const Algorithm & GetAlgorithm() const {return *this;} 1299 }; 1300 1301 /// \brief Interface for message authentication codes 1302 /// \details These objects usually should not be used directly. See HashTransformation for more details. 1303 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation 1304 { 1305 protected: 1306 const Algorithm & GetAlgorithm() const {return *this;} 1307 }; 1308 1309 /// \brief Interface for authenticated encryption modes of operation 1310 /// \details AuthenticatedSymmetricCipher() provides the interface for one direction 1311 /// (encryption or decryption) of a stream cipher or block cipher mode with authentication. The 1312 /// StreamTransformation() part of this interface is used to encrypt or decrypt the data. The 1313 /// MessageAuthenticationCode() part of the interface is used to input additional authenticated 1314 /// data (AAD), which is MAC'ed but not encrypted. The MessageAuthenticationCode() part is also 1315 /// used to generate and verify the MAC. 1316 /// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM 1317 /// and OCB mode. All modes implement AuthenticatedSymmetricCipher() and the motivation for 1318 /// the API, like calling AAD a "header", can be found in Bellare, Rogaway and 1319 /// Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX Mode of 1320 /// Operation</A>. The EAX paper suggested a basic API to help standardize AEAD schemes in 1321 /// software and promote adoption of the modes. 1322 /// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated 1323 /// Encryption</A> on the Crypto++ wiki. 1324 /// \since Crypto++ 5.6.0 1325 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation 1326 { 1327 public: 1328 virtual ~AuthenticatedSymmetricCipher() {} 1329 1330 /// \brief Exception thrown when the object is in the wrong state for the operation 1331 /// \details this indicates that a member function was called in the wrong state, for example trying to encrypt 1332 /// a message before having set the key or IV 1333 class BadState : public Exception 1334 { 1335 public: 1336 explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {} 1337 explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {} 1338 }; 1339 1340 /// \brief Provides the maximum length of AAD that can be input 1341 /// \return the maximum length of AAD that can be input before the encrypted data 1342 virtual lword MaxHeaderLength() const =0; 1343 1344 /// \brief Provides the maximum length of encrypted data 1345 /// \return the maximum length of encrypted data 1346 virtual lword MaxMessageLength() const =0; 1347 1348 /// \brief Provides the maximum length of AAD 1349 /// \return the maximum length of AAD that can be input after the encrypted data 1350 virtual lword MaxFooterLength() const {return 0;} 1351 1352 /// \brief Determines if data lengths must be specified prior to inputting data 1353 /// \return true if the data lengths are required before inputting data, false otherwise 1354 /// \details if this function returns true, SpecifyDataLengths() must be called before attempting to input data. 1355 /// This is the case for some schemes, such as CCM. 1356 /// \sa SpecifyDataLengths() 1357 virtual bool NeedsPrespecifiedDataLengths() const {return false;} 1358 1359 /// \brief Prescribes the data lengths 1360 /// \param headerLength size of data before message is input, in bytes 1361 /// \param messageLength size of the message, in bytes 1362 /// \param footerLength size of data after message is input, in bytes 1363 /// \details SpecifyDataLengths() only needs to be called if NeedsPrespecifiedDataLengths() returns <tt>true</tt>. 1364 /// If <tt>true</tt>, then <tt>headerLength</tt> will be validated against <tt>MaxHeaderLength()</tt>, 1365 /// <tt>messageLength</tt> will be validated against <tt>MaxMessageLength()</tt>, and 1366 /// <tt>footerLength</tt> will be validated against <tt>MaxFooterLength()</tt>. 1367 /// \sa NeedsPrespecifiedDataLengths() 1368 void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0); 1369 1370 /// \brief Encrypts and calculates a MAC in one call 1371 /// \param ciphertext the encryption buffer 1372 /// \param mac the mac buffer 1373 /// \param macSize the size of the MAC buffer, in bytes 1374 /// \param iv the iv buffer 1375 /// \param ivLength the size of the IV buffer, in bytes 1376 /// \param header the AAD buffer 1377 /// \param headerLength the size of the AAD buffer, in bytes 1378 /// \param message the message buffer 1379 /// \param messageLength the size of the messagetext buffer, in bytes 1380 /// \details EncryptAndAuthenticate() encrypts and generates the MAC in one call. The function 1381 /// truncates the MAC if <tt>macSize < TagSize()</tt>. 1382 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); 1383 1384 /// \brief Decrypts and verifies a MAC in one call 1385 /// \param message the decryption buffer 1386 /// \param mac the mac buffer 1387 /// \param macSize the size of the MAC buffer, in bytes 1388 /// \param iv the iv buffer 1389 /// \param ivLength the size of the IV buffer, in bytes 1390 /// \param header the AAD buffer 1391 /// \param headerLength the size of the AAD buffer, in bytes 1392 /// \param ciphertext the ciphertext buffer 1393 /// \param ciphertextLength the size of the ciphertext buffer, in bytes 1394 /// \return true if the MAC is valid and the decoding succeeded, false otherwise 1395 /// \details DecryptAndVerify() decrypts and verifies the MAC in one call. 1396 /// <tt>message</tt> is a decryption buffer and should be at least as large as the ciphertext buffer. 1397 /// \details The function returns true iff MAC is valid. DecryptAndVerify() assumes the MAC 1398 /// is truncated if <tt>macLength < TagSize()</tt>. 1399 virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength); 1400 1401 /// \brief Provides the name of this algorithm 1402 /// \return the standard algorithm name 1403 /// \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms 1404 /// do not have standard names yet. For example, there is no standard algorithm name for 1405 /// Shoup's ECIES. 1406 virtual std::string AlgorithmName() const; 1407 1408 /// \brief Retrieve the provider of this algorithm 1409 /// \return the algorithm provider 1410 /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI", 1411 /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE, 1412 /// usually indicate a specialized implementation using instructions from a higher 1413 /// instruction set architecture (ISA). Future labels may include external hardware 1414 /// like a hardware security module (HSM). 1415 /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2". 1416 /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics 1417 /// instead of ASM. 1418 /// \details Algorithms which combine different instructions or ISAs provide the 1419 /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than 1420 /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL". 1421 /// \note Provider is not universally implemented yet. 1422 /// \since Crypto++ 8.0 1423 virtual std::string AlgorithmProvider() const {return "C++";} 1424 1425 protected: 1426 const Algorithm & GetAlgorithm() const 1427 {return *static_cast<const MessageAuthenticationCode *>(this);} 1428 virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength) 1429 {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);} 1430 }; 1431 1432 /// \brief Interface for random number generators 1433 /// \details The library provides a number of random number generators, from software based 1434 /// to hardware based generators. 1435 /// \details All generated values are uniformly distributed over the range specified. 1436 /// \since Crypto++ 3.1 1437 /// \sa <A HREF="https://www.cryptopp.com/wiki/RandomNumberGenerator">RandomNumberGenerator</A> 1438 /// on the Crypto++ wiki 1439 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm 1440 { 1441 public: 1442 virtual ~RandomNumberGenerator() {} 1443 1444 /// \brief Update RNG state with additional unpredictable values 1445 /// \param input the entropy to add to the generator 1446 /// \param length the size of the input buffer 1447 /// \throw NotImplemented 1448 /// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy() 1449 /// to test for the ability to use additional entropy. 1450 /// \details If a derived class does not override IncorporateEntropy(), then the base class 1451 /// throws NotImplemented. 1452 virtual void IncorporateEntropy(const byte *input, size_t length) 1453 { 1454 CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length); 1455 throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented"); 1456 } 1457 1458 /// \brief Determines if a generator can accept additional entropy 1459 /// \return true if IncorporateEntropy() is implemented 1460 virtual bool CanIncorporateEntropy() const {return false;} 1461 1462 /// \brief Generate new random byte and return it 1463 /// \return a random 8-bit byte 1464 /// \details Default implementation calls GenerateBlock() with one byte. 1465 /// \details All generated values are uniformly distributed over the range specified within the 1466 /// the constraints of a particular generator. 1467 virtual byte GenerateByte(); 1468 1469 /// \brief Generate new random bit and return it 1470 /// \return a random bit 1471 /// \details The default implementation calls GenerateByte() and return its lowest bit. 1472 /// \details All generated values are uniformly distributed over the range specified within the 1473 /// the constraints of a particular generator. 1474 virtual unsigned int GenerateBit(); 1475 1476 /// \brief Generate a random 32 bit word in the range min to max, inclusive 1477 /// \param min the lower bound of the range 1478 /// \param max the upper bound of the range 1479 /// \return a random 32-bit word 1480 /// \details The default implementation calls Crop() on the difference between max and 1481 /// min, and then returns the result added to min. 1482 /// \details All generated values are uniformly distributed over the range specified within the 1483 /// the constraints of a particular generator. 1484 virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL); 1485 1486 /// \brief Generate random array of bytes 1487 /// \param output the byte buffer 1488 /// \param size the length of the buffer, in bytes 1489 /// \details All generated values are uniformly distributed over the range specified within the 1490 /// the constraints of a particular generator. 1491 /// \note A derived generator \a must override either GenerateBlock() or 1492 /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other. 1493 virtual void GenerateBlock(byte *output, size_t size); 1494 1495 /// \brief Generate random bytes into a BufferedTransformation 1496 /// \param target the BufferedTransformation object which receives the bytes 1497 /// \param channel the channel on which the bytes should be pumped 1498 /// \param length the number of bytes to generate 1499 /// \details The default implementation calls GenerateBlock() and pumps the result into 1500 /// the DEFAULT_CHANNEL of the target. 1501 /// \details All generated values are uniformly distributed over the range specified within the 1502 /// the constraints of a particular generator. 1503 /// \note A derived generator \a must override either GenerateBlock() or 1504 /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other. 1505 virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length); 1506 1507 /// \brief Generate and discard n bytes 1508 /// \param n the number of bytes to generate and discard 1509 virtual void DiscardBytes(size_t n); 1510 1511 /// \brief Randomly shuffle the specified array 1512 /// \param begin an iterator to the first element in the array 1513 /// \param end an iterator beyond the last element in the array 1514 /// \details The resulting permutation is uniformly distributed. 1515 template <class IT> void Shuffle(IT begin, IT end) 1516 { 1517 // TODO: What happens if there are more than 2^32 elements? 1518 for (; begin != end; ++begin) 1519 std::iter_swap(begin, begin + GenerateWord32(0, static_cast<word32>(end-begin-1))); 1520 } 1521 }; 1522 1523 /// \brief Interface for key derivation functions 1524 /// \since Crypto++ 7.0 1525 /// \sa <A HREF="https://www.cryptopp.com/wiki/KeyDerivationFunction">KeyDerivationFunction</A> 1526 /// on the Crypto++ wiki 1527 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm 1528 { 1529 public: 1530 virtual ~KeyDerivationFunction() {} 1531 1532 /// \brief Provides the name of this algorithm 1533 /// \return the standard algorithm name 1534 virtual std::string AlgorithmName() const =0; 1535 1536 /// \brief Determine minimum number of bytes 1537 /// \return Minimum number of bytes which can be derived 1538 virtual size_t MinDerivedKeyLength() const; 1539 1540 /// \brief Determine maximum number of bytes 1541 /// \return Maximum number of bytes which can be derived 1542 virtual size_t MaxDerivedKeyLength() const; 1543 1544 /// \brief Returns a valid key length for the derivation function 1545 /// \param keylength the size of the derived key, in bytes 1546 /// \return the valid key length, in bytes 1547 virtual size_t GetValidDerivedLength(size_t keylength) const =0; 1548 1549 /// \brief Returns whether keylength is a valid key length 1550 /// \param keylength the requested keylength 1551 /// \return true if the derived keylength is valid, false otherwise 1552 /// \details Internally the function calls GetValidKeyLength() 1553 virtual bool IsValidDerivedLength(size_t keylength) const { 1554 return keylength == GetValidDerivedLength(keylength); 1555 } 1556 1557 /// \brief Derive a key from a seed 1558 /// \param derived the derived output buffer 1559 /// \param derivedLen the size of the derived buffer, in bytes 1560 /// \param secret the seed input buffer 1561 /// \param secretLen the size of the secret buffer, in bytes 1562 /// \param params additional initialization parameters to configure this object 1563 /// \return the number of iterations performed 1564 /// \throw InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme 1565 /// \details DeriveKey() provides a standard interface to derive a key from 1566 /// a secret seed and other parameters. Each class that derives from KeyDerivationFunction 1567 /// provides an overload that accepts most parameters used by the derivation function. 1568 /// \details the number of iterations performed by DeriveKey() may be 1. For example, a 1569 /// scheme like HKDF does not use the iteration count so it returns 1. 1570 virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params = g_nullNameValuePairs) const =0; 1571 1572 /// \brief Set or change parameters 1573 /// \param params additional initialization parameters to configure this object 1574 /// \details SetParameters() is useful for setting common parameters when an object is 1575 /// reused. Some derivation function classes may choose to implement it. 1576 virtual void SetParameters(const NameValuePairs& params); 1577 1578 protected: 1579 /// \brief Returns the base class Algorithm 1580 /// \return the base class Algorithm 1581 virtual const Algorithm & GetAlgorithm() const =0; 1582 1583 /// \brief Validates the derived key length 1584 /// \param length the size of the derived key material, in bytes 1585 /// \throw InvalidKeyLength if the key length is invalid 1586 void ThrowIfInvalidDerivedKeyLength(size_t length) const; 1587 }; 1588 1589 /// \brief Interface for password based key derivation functions 1590 /// \since Crypto++ 7.0 1591 struct PasswordBasedKeyDerivationFunction : public KeyDerivationFunction 1592 { 1593 }; 1594 1595 /// \brief Random Number Generator that does not produce random numbers 1596 /// \return reference that can be passed to functions that require a RandomNumberGenerator 1597 /// \details NullRNG() returns a reference that can be passed to functions that require a 1598 /// RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented 1599 /// when a generation function is called. 1600 /// \sa ClassNullRNG, PK_SignatureScheme::IsProbabilistic() 1601 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG(); 1602 1603 class WaitObjectContainer; 1604 class CallStack; 1605 1606 /// \brief Interface for objects that can be waited on. 1607 class CRYPTOPP_NO_VTABLE Waitable 1608 { 1609 public: 1610 virtual ~Waitable() {} 1611 1612 /// \brief Maximum number of wait objects that this object can return 1613 /// \return the maximum number of wait objects 1614 virtual unsigned int GetMaxWaitObjectCount() const =0; 1615 1616 /// \brief Retrieves waitable objects 1617 /// \param container the wait container to receive the references to the objects. 1618 /// \param callStack CallStack() object used to select waitable objects 1619 /// \details GetWaitObjects() is usually called in one of two ways. First, it can 1620 /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>. 1621 /// Second, if in an outer GetWaitObjects() method that itself takes a callStack 1622 /// parameter, it can be called like 1623 /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>. 1624 virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0; 1625 1626 /// \brief Wait on this object 1627 /// \return true if the wait succeeded, false otherwise 1628 /// \details Wait() is the same as creating an empty container, calling GetWaitObjects(), and then calling 1629 /// Wait() on the container. 1630 bool Wait(unsigned long milliseconds, CallStack const& callStack); 1631 }; 1632 1633 /// \brief Interface for buffered transformations 1634 /// \details BufferedTransformation is a generalization of BlockTransformation, 1635 /// StreamTransformation and HashTransformation. 1636 /// \details A buffered transformation is an object that takes a stream of bytes as input (this may 1637 /// be done in stages), does some computation on them, and then places the result into an internal 1638 /// buffer for later retrieval. Any partial result already in the output buffer is not modified 1639 /// by further input. 1640 /// \details If a method takes a "blocking" parameter, and you pass false for it, then the method 1641 /// will return before all input has been processed if the input cannot be processed without waiting 1642 /// (for network buffers to become available, for example). In this case the method will return true 1643 /// or a non-zero integer value. When this happens you must continue to call the method with the same 1644 /// parameters until it returns false or zero, before calling any other method on it or attached 1645 /// BufferedTransformation. The integer return value in this case is approximately 1646 /// the number of bytes left to be processed, and can be used to implement a progress bar. 1647 /// \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on 1648 /// the signal to attached BufferedTransformation objects, with propagation decremented at each 1649 /// step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation. 1650 /// \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual 1651 /// number of bytes retrieved, which is the lesser of the request number and MaxRetrievable(). 1652 /// \details \a Most of the input functions, like Put() and PutWord32(), return the number of 1653 /// bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value 1654 /// means bytes remain to be processed. 1655 /// \nosubgrouping 1656 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable 1657 { 1658 public: 1659 virtual ~BufferedTransformation() {} 1660 1661 /// \brief Construct a BufferedTransformation 1662 BufferedTransformation() : Algorithm(false) {} 1663 1664 /// \brief Provides a reference to this object 1665 /// \return A reference to this object 1666 /// \details Useful for passing a temporary object to a function that takes a non-const reference 1667 BufferedTransformation& Ref() {return *this;} 1668 1669 /// \name INPUT 1670 //@{ 1671 1672 /// \brief Input a byte for processing 1673 /// \param inByte the 8-bit byte (octet) to be processed. 1674 /// \param blocking specifies whether the object should block when processing input. 1675 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 1676 /// 0 indicates all bytes were processed. 1677 /// \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>. 1678 size_t Put(byte inByte, bool blocking=true) 1679 {return Put(&inByte, 1, blocking);} 1680 1681 /// \brief Input a byte buffer for processing 1682 /// \param inString the byte buffer to process 1683 /// \param length the size of the string, in bytes 1684 /// \param blocking specifies whether the object should block when processing input 1685 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 1686 /// 0 indicates all bytes were processed. 1687 /// \details Internally, Put() calls Put2(). 1688 size_t Put(const byte *inString, size_t length, bool blocking=true) 1689 {return Put2(inString, length, 0, blocking);} 1690 1691 /// Input a 16-bit word for processing. 1692 /// \param value the 16-bit value to be processed 1693 /// \param order the ByteOrder of the value to be processed. 1694 /// \param blocking specifies whether the object should block when processing input 1695 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 1696 /// 0 indicates all bytes were processed. 1697 size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 1698 1699 /// Input a 32-bit word for processing. 1700 /// \param value the 32-bit value to be processed. 1701 /// \param order the ByteOrder of the value to be processed. 1702 /// \param blocking specifies whether the object should block when processing input. 1703 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 1704 /// 0 indicates all bytes were processed. 1705 size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 1706 1707 /// Input a 64-bit word for processing. 1708 /// \param value the 64-bit value to be processed. 1709 /// \param order the ByteOrder of the value to be processed. 1710 /// \param blocking specifies whether the object should block when processing input. 1711 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 1712 /// 0 indicates all bytes were processed. 1713 size_t PutWord64(word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 1714 1715 /// \brief Request space which can be written into by the caller 1716 /// \param size the requested size of the buffer 1717 /// \return byte pointer to the space to input data 1718 /// \details The purpose of this method is to help avoid extra memory allocations. 1719 /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made, 1720 /// size is the requested size of the buffer. When the call returns, size is the size of 1721 /// the array returned to the caller. 1722 /// \details The base class implementation sets size to 0 and returns NULL. 1723 /// \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of 1724 /// an ArraySink, the pointer to the array is returned and the size is remaining size. 1725 virtual byte * CreatePutSpace(size_t &size) 1726 {size=0; return NULLPTR;} 1727 1728 /// \brief Determines whether input can be modified by the callee 1729 /// \return true if input can be modified, false otherwise 1730 /// \details The base class implementation returns false. 1731 virtual bool CanModifyInput() const 1732 {return false;} 1733 1734 /// \brief Input multiple bytes that may be modified by callee. 1735 /// \param inString the byte buffer to process 1736 /// \param length the size of the string, in bytes 1737 /// \param blocking specifies whether the object should block when processing input 1738 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all 1739 /// bytes were processed. 1740 size_t PutModifiable(byte *inString, size_t length, bool blocking=true) 1741 {return PutModifiable2(inString, length, 0, blocking);} 1742 1743 /// \brief Signals the end of messages to the object 1744 /// \param propagation the number of attached transformations the MessageEnd() signal should be passed 1745 /// \param blocking specifies whether the object should block when processing input 1746 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 1747 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 1748 bool MessageEnd(int propagation=-1, bool blocking=true) 1749 {return !!Put2(NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);} 1750 1751 /// \brief Input multiple bytes for processing and signal the end of a message 1752 /// \param inString the byte buffer to process 1753 /// \param length the size of the string, in bytes 1754 /// \param propagation the number of attached transformations the MessageEnd() signal should be passed 1755 /// \param blocking specifies whether the object should block when processing input 1756 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all 1757 /// bytes were processed. 1758 /// \details Internally, PutMessageEnd() calls Put2() with a modified propagation to 1759 /// ensure all attached transformations finish processing the message. 1760 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 1761 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 1762 size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true) 1763 {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);} 1764 1765 /// \brief Input multiple bytes for processing 1766 /// \param inString the byte buffer to process 1767 /// \param length the size of the string, in bytes 1768 /// \param messageEnd means how many filters to signal MessageEnd() to, including this one 1769 /// \param blocking specifies whether the object should block when processing input 1770 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all 1771 /// bytes were processed. 1772 /// \details Derived classes must implement Put2(). 1773 virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0; 1774 1775 /// \brief Input multiple bytes that may be modified by callee. 1776 /// \param inString the byte buffer to process. 1777 /// \param length the size of the string, in bytes. 1778 /// \param messageEnd means how many filters to signal MessageEnd() to, including this one. 1779 /// \param blocking specifies whether the object should block when processing input. 1780 /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all 1781 /// bytes were processed. 1782 /// \details Internally, PutModifiable2() calls Put2(). 1783 virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking) 1784 {return Put2(inString, length, messageEnd, blocking);} 1785 1786 /// \brief Exception thrown by objects that have \a not implemented nonblocking input processing 1787 /// \details BlockingInputOnly inherits from NotImplemented 1788 struct BlockingInputOnly : public NotImplemented 1789 {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}}; 1790 //@} 1791 1792 /// \name WAITING 1793 //@{ 1794 /// \brief Retrieves the maximum number of waitable objects 1795 unsigned int GetMaxWaitObjectCount() const; 1796 1797 /// \brief Retrieves waitable objects 1798 /// \param container the wait container to receive the references to the objects 1799 /// \param callStack CallStack() object used to select waitable objects 1800 /// \details GetWaitObjects is usually called in one of two ways. First, it can 1801 /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>. 1802 /// Second, if in an outer GetWaitObjects() method that itself takes a callStack 1803 /// parameter, it can be called like 1804 /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>. 1805 void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack); 1806 //@} // WAITING 1807 1808 /// \name SIGNALS 1809 //@{ 1810 1811 /// \brief Initialize or reinitialize this object, without signal propagation 1812 /// \param parameters a set of NameValuePairs to initialize this object 1813 /// \throw NotImplemented 1814 /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable 1815 /// number of arbitrarily typed arguments. The function avoids the need for multiple constructors providing 1816 /// all possible combintations of configurable parameters. 1817 /// \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization 1818 /// should be propagated, then use the Initialize() function. 1819 /// \details If a derived class does not override IsolatedInitialize(), then the base class throws 1820 /// NotImplemented. 1821 virtual void IsolatedInitialize(const NameValuePairs ¶meters) { 1822 CRYPTOPP_UNUSED(parameters); 1823 throw NotImplemented("BufferedTransformation: this object can't be reinitialized"); 1824 } 1825 1826 /// \brief Flushes data buffered by this object, without signal propagation 1827 /// \param hardFlush indicates whether all data should be flushed 1828 /// \param blocking specifies whether the object should block when processing input 1829 /// \return true if the flush was successful, false otherwise 1830 /// \note hardFlush must be used with care 1831 virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0; 1832 1833 /// \brief Marks the end of a series of messages, without signal propagation 1834 /// \param blocking specifies whether the object should block when completing the processing on 1835 /// the current series of messages 1836 /// \return true if the message was successful, false otherwise 1837 virtual bool IsolatedMessageSeriesEnd(bool blocking) 1838 {CRYPTOPP_UNUSED(blocking); return false;} 1839 1840 /// \brief Initialize or reinitialize this object, with signal propagation 1841 /// \param parameters a set of NameValuePairs to initialize or reinitialize this object 1842 /// \param propagation the number of attached transformations the Initialize() signal should be passed 1843 /// \details Initialize() is used to initialize or reinitialize an object using a variable number of 1844 /// arbitrarily typed arguments. The function avoids the need for multiple constructors providing 1845 /// all possible combintations of configurable parameters. 1846 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 1847 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 1848 virtual void Initialize(const NameValuePairs ¶meters=g_nullNameValuePairs, int propagation=-1); 1849 1850 /// \brief Flush buffered input and/or output, with signal propagation 1851 /// \param hardFlush is used to indicate whether all data should be flushed 1852 /// \param propagation the number of attached transformations the Flush() 1853 /// signal should be passed 1854 /// \param blocking specifies whether the object should block when processing input 1855 /// \return true if the flush was successful, false otherwise 1856 /// \details propagation count includes this object. Setting propagation to 1857 /// <tt>1</tt> means this object only. Setting propagation to <tt>-1</tt> 1858 /// means unlimited propagation. 1859 /// \note Hard flushes must be used with care. It means try to process and 1860 /// output everything, even if there may not be enough data to complete the 1861 /// action. For example, hard flushing a HexDecoder would cause an error if 1862 /// you do it after inputing an odd number of hex encoded characters. 1863 /// \note For some types of filters, like ZlibDecompressor, hard flushes can 1864 /// only be done at "synchronization points". These synchronization points 1865 /// are positions in the data stream that are created by hard flushes on the 1866 /// corresponding reverse filters, in this example ZlibCompressor. This is 1867 /// useful when zlib compressed data is moved across a network in packets 1868 /// and compression state is preserved across packets, as in the SSH2 protocol. 1869 virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true); 1870 1871 /// \brief Marks the end of a series of messages, with signal propagation 1872 /// \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed 1873 /// \param blocking specifies whether the object should block when processing input 1874 /// \return true if the message was successful, false otherwise 1875 /// \details Each object that receives the signal will perform its processing, decrement 1876 /// propagation, and then pass the signal on to attached transformations if the value is not 0. 1877 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 1878 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 1879 /// \note There should be a MessageEnd() immediately before MessageSeriesEnd(). 1880 virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true); 1881 1882 /// \brief Set propagation of automatically generated and transferred signals 1883 /// \param propagation then new value 1884 /// \details Setting propagation to <tt>0</tt> means do not automatically generate signals. Setting 1885 /// propagation to <tt>-1</tt> means unlimited propagation. 1886 virtual void SetAutoSignalPropagation(int propagation) 1887 {CRYPTOPP_UNUSED(propagation);} 1888 1889 /// \brief Retrieve automatic signal propagation value 1890 /// \return the number of attached transformations the signal is propagated to. 0 indicates 1891 /// the signal is only witnessed by this object 1892 virtual int GetAutoSignalPropagation() const {return 0;} 1893 public: 1894 1895 /// \name RETRIEVAL OF ONE MESSAGE 1896 //@{ 1897 1898 /// \brief Provides the number of bytes ready for retrieval 1899 /// \return the number of bytes ready for retrieval 1900 /// \details The number of bytes available are dependent on the source. If an exact value is 1901 /// available, then the exact value is returned. The exact value can include 0 if the source 1902 /// is exhausted. 1903 /// \details Some stream-based sources do not allow seeking() on the underlying stream, such 1904 /// as some FileSource(). If the stream does not allow seeking() then MaxRetrievable() 1905 /// returns LWORD_MAX to indicate there are still bytes to be retrieved. 1906 virtual lword MaxRetrievable() const; 1907 1908 /// \brief Determines whether bytes are ready for retrieval 1909 /// \return true if bytes are available for retrieval, false otherwise 1910 virtual bool AnyRetrievable() const; 1911 1912 /// \brief Retrieve a 8-bit byte 1913 /// \param outByte the 8-bit value to be retrieved 1914 /// \return the number of bytes consumed during the call. 1915 /// \details Use the return value of Get to detect short reads. 1916 virtual size_t Get(byte &outByte); 1917 1918 /// \brief Retrieve a block of bytes 1919 /// \param outString a block of bytes 1920 /// \param getMax the number of bytes to Get 1921 /// \return the number of bytes consumed during the call. 1922 /// \details Use the return value of Get to detect short reads. 1923 virtual size_t Get(byte *outString, size_t getMax); 1924 1925 /// \brief Peek a 8-bit byte 1926 /// \param outByte the 8-bit value to be retrieved 1927 /// \return the number of bytes read during the call. 1928 /// \details Peek does not remove bytes from the object. Use the return value of 1929 /// Get() to detect short reads. 1930 virtual size_t Peek(byte &outByte) const; 1931 1932 /// \brief Peek a block of bytes 1933 /// \param outString a block of bytes 1934 /// \param peekMax the number of bytes to Peek 1935 /// \return the number of bytes read during the call. 1936 /// \details Peek does not remove bytes from the object. Use the return value of 1937 /// Peek() to detect short reads. 1938 virtual size_t Peek(byte *outString, size_t peekMax) const; 1939 1940 /// \brief Retrieve a 16-bit word 1941 /// \param value the 16-bit value to be retrieved 1942 /// \param order the ByteOrder of the value to be processed. 1943 /// \return the number of bytes consumed during the call. 1944 /// \details Use the return value of GetWord16() to detect short reads. 1945 size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER); 1946 1947 /// \brief Retrieve a 32-bit word 1948 /// \param value the 32-bit value to be retrieved 1949 /// \param order the ByteOrder of the value to be processed. 1950 /// \return the number of bytes consumed during the call. 1951 /// \details Use the return value of GetWord32() to detect short reads. 1952 size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER); 1953 1954 /// \brief Retrieve a 64-bit word 1955 /// \param value the 64-bit value to be retrieved 1956 /// \param order the ByteOrder of the value to be processed. 1957 /// \return the number of bytes consumed during the call. 1958 /// \details Use the return value of GetWord64() to detect short reads. 1959 /// \since Crypto++ 8.3 1960 size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER); 1961 1962 /// \brief Peek a 16-bit word 1963 /// \param value the 16-bit value to be retrieved 1964 /// \param order the ByteOrder of the value to be processed. 1965 /// \return the number of bytes consumed during the call. 1966 /// \details Peek does not consume bytes in the stream. Use the return value 1967 /// of PeekWord16() to detect short reads. 1968 size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const; 1969 1970 /// \brief Peek a 32-bit word 1971 /// \param value the 32-bit value to be retrieved 1972 /// \param order the ByteOrder of the value to be processed. 1973 /// \return the number of bytes consumed during the call. 1974 /// \details Peek does not consume bytes in the stream. Use the return value 1975 /// of PeekWord32() to detect short reads. 1976 size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const; 1977 1978 /// \brief Peek a 64-bit word 1979 /// \param value the 64-bit value to be retrieved 1980 /// \param order the ByteOrder of the value to be processed. 1981 /// \return the number of bytes consumed during the call. 1982 /// \details Peek does not consume bytes in the stream. Use the return value 1983 /// of PeekWord64() to detect short reads. 1984 /// \since Crypto++ 8.3 1985 size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const; 1986 1987 /// move transferMax bytes of the buffered output to target as input 1988 1989 /// \brief Transfer bytes from this object to another BufferedTransformation 1990 /// \param target the destination BufferedTransformation 1991 /// \param transferMax the number of bytes to transfer 1992 /// \param channel the channel on which the transfer should occur 1993 /// \return the number of bytes transferred during the call. 1994 /// \details TransferTo removes bytes from this object and moves them to the destination. 1995 /// \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2(). 1996 lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) 1997 {TransferTo2(target, transferMax, channel); return transferMax;} 1998 1999 /// \brief Discard skipMax bytes from the output buffer 2000 /// \param skipMax the number of bytes to discard 2001 /// \details Skip() discards bytes from the output buffer, which is the AttachedTransformation(), if present. 2002 /// The function always returns the parameter <tt>skipMax</tt>. 2003 /// \details If you want to skip bytes from a Source, then perform the following. 2004 /// <pre> StringSource ss(str, false, new Redirector(TheBitBucket())); 2005 /// ss.Pump(10); // Skip 10 bytes from Source 2006 /// ss.Detach(new FilterChain(...)); 2007 /// ss.PumpAll(); 2008 /// </pre> 2009 virtual lword Skip(lword skipMax=LWORD_MAX); 2010 2011 /// \brief Copy bytes from this object to another BufferedTransformation 2012 /// \param target the destination BufferedTransformation 2013 /// \param copyMax the number of bytes to copy 2014 /// \param channel the channel on which the transfer should occur 2015 /// \return the number of bytes copied during the call. 2016 /// \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object. 2017 /// \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2(). 2018 lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const 2019 {return CopyRangeTo(target, 0, copyMax, channel);} 2020 2021 /// \brief Copy bytes from this object using an index to another BufferedTransformation 2022 /// \param target the destination BufferedTransformation 2023 /// \param position the 0-based index of the byte stream to begin the copying 2024 /// \param copyMax the number of bytes to copy 2025 /// \param channel the channel on which the transfer should occur 2026 /// \return the number of bytes copied during the call. 2027 /// \details CopyTo copies bytes from this object to the destination. The bytes remain in this 2028 /// object. Copying begins at the index position in the current stream, and not from an absolute 2029 /// position in the stream. 2030 /// \details The function returns the new position in the stream after transferring the bytes starting at the index. 2031 lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const 2032 {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;} 2033 //@} 2034 2035 /// \name RETRIEVAL OF MULTIPLE MESSAGES 2036 //@{ 2037 2038 /// \brief Provides the number of bytes ready for retrieval 2039 /// \return the number of bytes ready for retrieval 2040 virtual lword TotalBytesRetrievable() const; 2041 2042 /// \brief Provides the number of meesages processed by this object 2043 /// \return the number of meesages processed by this object 2044 /// \details NumberOfMessages returns number of times MessageEnd() has been 2045 /// received minus messages retrieved or skipped 2046 virtual unsigned int NumberOfMessages() const; 2047 2048 /// \brief Determines if any messages are available for retrieval 2049 /// \return true if <tt>NumberOfMessages() > 0</tt>, false otherwise 2050 /// \details AnyMessages returns true if <tt>NumberOfMessages() > 0</tt> 2051 virtual bool AnyMessages() const; 2052 2053 /// \brief Start retrieving the next message 2054 /// \return true if a message is ready for retrieval 2055 /// \details GetNextMessage() returns true if a message is ready for retrieval; false 2056 /// if no more messages exist or this message is not completely retrieved. 2057 virtual bool GetNextMessage(); 2058 2059 /// \brief Skip a number of meessages 2060 /// \param count number of messages to skip 2061 /// \return 0 if the requested number of messages was skipped, non-0 otherwise 2062 /// \details SkipMessages() skips count number of messages. If there is an AttachedTransformation() 2063 /// then SkipMessages() is called on the attached transformation. If there is no attached 2064 /// transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo(). 2065 virtual unsigned int SkipMessages(unsigned int count=UINT_MAX); 2066 2067 /// \brief Transfer messages from this object to another BufferedTransformation 2068 /// \param target the destination BufferedTransformation 2069 /// \param count the number of messages to transfer 2070 /// \param channel the channel on which the transfer should occur 2071 /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 2072 /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination. 2073 /// If all bytes are not transferred for a message, then processing stops and the number of remaining 2074 /// bytes is returned. TransferMessagesTo() does not proceed to the next message. 2075 /// \details A return value of 0 indicates all messages were successfully transferred. 2076 unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) 2077 {TransferMessagesTo2(target, count, channel); return count;} 2078 2079 /// \brief Copy messages from this object to another BufferedTransformation 2080 /// \param target the destination BufferedTransformation 2081 /// \param count the number of messages to copy 2082 /// \param channel the channel on which the copy should occur 2083 /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 2084 /// \details CopyMessagesTo copies messages from this object to the destination. 2085 /// If all bytes are not transferred for a message, then processing stops and the number of remaining 2086 /// bytes is returned. CopyMessagesTo() does not proceed to the next message. 2087 /// \details A return value of 0 indicates all messages were successfully copied. 2088 unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const; 2089 2090 /// \brief Skip all messages in the series 2091 virtual void SkipAll(); 2092 2093 /// \brief Transfer all bytes from this object to another BufferedTransformation 2094 /// \param target the destination BufferedTransformation 2095 /// \param channel the channel on which the transfer should occur 2096 /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination. 2097 /// Internally TransferAllTo() calls TransferAllTo2(). 2098 void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) 2099 {TransferAllTo2(target, channel);} 2100 2101 /// \brief Copy messages from this object to another BufferedTransformation 2102 /// \param target the destination BufferedTransformation 2103 /// \param channel the channel on which the transfer should occur 2104 /// \details CopyAllTo copies messages from this object and copies them to the destination. 2105 void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const; 2106 2107 /// \brief Retrieve the next message in a series 2108 /// \return true if a message was retrieved, false otherwise 2109 /// \details Internally, the base class implementation returns false. 2110 virtual bool GetNextMessageSeries() {return false;} 2111 /// \brief Provides the number of messages in a series 2112 /// \return the number of messages in this series 2113 virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();} 2114 /// \brief Provides the number of messages in a series 2115 /// \return the number of messages in this series 2116 virtual unsigned int NumberOfMessageSeries() const {return 0;} 2117 //@} 2118 2119 /// \name NON-BLOCKING TRANSFER OF OUTPUT 2120 //@{ 2121 2122 // upon return, byteCount contains number of bytes that have finished being transferred, 2123 // and returns the number of bytes left in the current transfer block 2124 2125 /// \brief Transfer bytes from this object to another BufferedTransformation 2126 /// \param target the destination BufferedTransformation 2127 /// \param byteCount the number of bytes to transfer 2128 /// \param channel the channel on which the transfer should occur 2129 /// \param blocking specifies whether the object should block when processing input 2130 /// \return the number of bytes that remain in the transfer block (i.e., bytes not transferred) 2131 /// \details TransferTo2() removes bytes from this object and moves them to the destination. 2132 /// Transfer begins at the index position in the current stream, and not from an absolute 2133 /// position in the stream. 2134 /// \details byteCount is an \a IN and \a OUT parameter. When the call is made, 2135 /// byteCount is the requested size of the transfer. When the call returns, byteCount is 2136 /// the number of bytes that were transferred. 2137 virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0; 2138 2139 // upon return, begin contains the start position of data yet to be finished copying, 2140 // and returns the number of bytes left in the current transfer block 2141 2142 /// \brief Copy bytes from this object to another BufferedTransformation 2143 /// \param target the destination BufferedTransformation 2144 /// \param begin the 0-based index of the first byte to copy in the stream 2145 /// \param end the 0-based index of the last byte to copy in the stream 2146 /// \param channel the channel on which the transfer should occur 2147 /// \param blocking specifies whether the object should block when processing input 2148 /// \return the number of bytes that remain in the copy block (i.e., bytes not copied) 2149 /// \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not 2150 /// removed from this object. Copying begins at the index position in the current stream, and 2151 /// not from an absolute position in the stream. 2152 /// \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the 2153 /// starting position of the copy. When the call returns, begin is the position of the first 2154 /// byte that was \a not copied (which may be different than end). begin can be used for 2155 /// subsequent calls to CopyRangeTo2(). 2156 virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0; 2157 2158 // upon return, messageCount contains number of messages that have finished being transferred, 2159 // and returns the number of bytes left in the current transfer block 2160 2161 /// \brief Transfer messages from this object to another BufferedTransformation 2162 /// \param target the destination BufferedTransformation 2163 /// \param messageCount the number of messages to transfer 2164 /// \param channel the channel on which the transfer should occur 2165 /// \param blocking specifies whether the object should block when processing input 2166 /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 2167 /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination. 2168 /// \details messageCount is an \a IN and \a OUT parameter. When the call is made, messageCount is the 2169 /// the number of messages requested to be transferred. When the call returns, messageCount is the 2170 /// number of messages actually transferred. 2171 size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true); 2172 2173 // returns the number of bytes left in the current transfer block 2174 2175 /// \brief Transfer all bytes from this object to another BufferedTransformation 2176 /// \param target the destination BufferedTransformation 2177 /// \param channel the channel on which the transfer should occur 2178 /// \param blocking specifies whether the object should block when processing input 2179 /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred) 2180 /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination. 2181 size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true); 2182 //@} 2183 2184 /// \name CHANNELS 2185 //@{ 2186 /// \brief Exception thrown when a filter does not support named channels 2187 struct NoChannelSupport : public NotImplemented 2188 {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}}; 2189 /// \brief Exception thrown when a filter does not recognize a named channel 2190 struct InvalidChannelName : public InvalidArgument 2191 {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}}; 2192 2193 /// \brief Input a byte for processing on a channel 2194 /// \param channel the channel to process the data. 2195 /// \param inByte the 8-bit byte (octet) to be processed. 2196 /// \param blocking specifies whether the object should block when processing input. 2197 /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the 2198 /// number of bytes that were not processed. 2199 size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true) 2200 {return ChannelPut(channel, &inByte, 1, blocking);} 2201 2202 /// \brief Input a byte buffer for processing on a channel 2203 /// \param channel the channel to process the data 2204 /// \param inString the byte buffer to process 2205 /// \param length the size of the string, in bytes 2206 /// \param blocking specifies whether the object should block when processing input 2207 /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the 2208 /// number of bytes that were not processed. 2209 size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true) 2210 {return ChannelPut2(channel, inString, length, 0, blocking);} 2211 2212 /// \brief Input multiple bytes that may be modified by callee on a channel 2213 /// \param channel the channel to process the data. 2214 /// \param inString the byte buffer to process 2215 /// \param length the size of the string, in bytes 2216 /// \param blocking specifies whether the object should block when processing input 2217 /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the 2218 /// number of bytes that were not processed. 2219 size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true) 2220 {return ChannelPutModifiable2(channel, inString, length, 0, blocking);} 2221 2222 /// \brief Input a 16-bit word for processing on a channel. 2223 /// \param channel the channel to process the data. 2224 /// \param value the 16-bit value to be processed. 2225 /// \param order the ByteOrder of the value to be processed. 2226 /// \param blocking specifies whether the object should block when processing input. 2227 /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the 2228 /// number of bytes that were not processed. 2229 size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 2230 2231 /// \brief Input a 32-bit word for processing on a channel. 2232 /// \param channel the channel to process the data. 2233 /// \param value the 32-bit value to be processed. 2234 /// \param order the ByteOrder of the value to be processed. 2235 /// \param blocking specifies whether the object should block when processing input. 2236 /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the 2237 /// number of bytes that were not processed. 2238 size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 2239 2240 /// \brief Input a 64-bit word for processing on a channel. 2241 /// \param channel the channel to process the data. 2242 /// \param value the 64-bit value to be processed. 2243 /// \param order the ByteOrder of the value to be processed. 2244 /// \param blocking specifies whether the object should block when processing input. 2245 /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the 2246 /// number of bytes that were not processed. 2247 size_t ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true); 2248 2249 /// \brief Signal the end of a message 2250 /// \param channel the channel to process the data. 2251 /// \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed 2252 /// \param blocking specifies whether the object should block when processing input 2253 /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the 2254 /// number of bytes that were not processed. 2255 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 2256 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 2257 bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true) 2258 {return !!ChannelPut2(channel, NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);} 2259 2260 /// \brief Input multiple bytes for processing and signal the end of a message 2261 /// \param channel the channel to process the data. 2262 /// \param inString the byte buffer to process 2263 /// \param length the size of the string, in bytes 2264 /// \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed 2265 /// \param blocking specifies whether the object should block when processing input 2266 /// \return the number of bytes that remain to be processed (i.e., bytes not processed) 2267 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 2268 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 2269 size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true) 2270 {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);} 2271 2272 /// \brief Request space which can be written into by the caller 2273 /// \param channel the channel to process the data 2274 /// \param size the requested size of the buffer 2275 /// \return a pointer to a memory block with length size 2276 /// \details The purpose of this method is to help avoid extra memory allocations. 2277 /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made, 2278 /// size is the requested size of the buffer. When the call returns, size is the size of 2279 /// the array returned to the caller. 2280 /// \details The base class implementation sets size to 0 and returns NULL. 2281 /// \note Some objects, like ArraySink(), cannot create a space because its fixed. In the case of 2282 /// an ArraySink(), the pointer to the array is returned and the size is remaining size. 2283 virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size); 2284 2285 /// \brief Input multiple bytes for processing on a channel. 2286 /// \param channel the channel to process the data. 2287 /// \param inString the byte buffer to process. 2288 /// \param length the size of the string, in bytes. 2289 /// \param messageEnd means how many filters to signal MessageEnd() to, including this one. 2290 /// \param blocking specifies whether the object should block when processing input. 2291 /// \return the number of bytes that remain to be processed (i.e., bytes not processed) 2292 virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking); 2293 2294 /// \brief Input multiple bytes that may be modified by callee on a channel 2295 /// \param channel the channel to process the data 2296 /// \param inString the byte buffer to process 2297 /// \param length the size of the string, in bytes 2298 /// \param messageEnd means how many filters to signal MessageEnd() to, including this one 2299 /// \param blocking specifies whether the object should block when processing input 2300 /// \return the number of bytes that remain to be processed (i.e., bytes not processed) 2301 virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking); 2302 2303 /// \brief Flush buffered input and/or output on a channel 2304 /// \param channel the channel to flush the data 2305 /// \param hardFlush is used to indicate whether all data should be flushed 2306 /// \param propagation the number of attached transformations the ChannelFlush() signal should be passed 2307 /// \param blocking specifies whether the object should block when processing input 2308 /// \return true of the Flush was successful 2309 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 2310 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 2311 virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true); 2312 2313 /// \brief Marks the end of a series of messages on a channel 2314 /// \param channel the channel to signal the end of a series of messages 2315 /// \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed 2316 /// \param blocking specifies whether the object should block when processing input 2317 /// \return true if the message was successful, false otherwise 2318 /// \details Each object that receives the signal will perform its processing, decrement 2319 /// propagation, and then pass the signal on to attached transformations if the value is not 0. 2320 /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this 2321 /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation. 2322 /// \note There should be a MessageEnd() immediately before MessageSeriesEnd(). 2323 virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true); 2324 2325 /// \brief Sets the default retrieval channel 2326 /// \param channel the channel to signal the end of a series of messages 2327 /// \note this function may not be implemented in all objects that should support it. 2328 virtual void SetRetrievalChannel(const std::string &channel); 2329 //@} 2330 2331 /// \name ATTACHMENT 2332 /// \details Some BufferedTransformation objects (e.g. Filter objects) allow other BufferedTransformation objects to be 2333 /// attached. When this is done, the first object instead of buffering its output, sends that output to the attached 2334 /// object as input. The entire attachment chain is deleted when the anchor object is destructed. 2335 2336 //@{ 2337 /// \brief Determines whether the object allows attachment 2338 /// \return true if the object allows an attachment, false otherwise 2339 /// \details Sources and Filters will returns true, while Sinks and other objects will return false. 2340 virtual bool Attachable() {return false;} 2341 2342 /// \brief Returns the object immediately attached to this object 2343 /// \return the attached transformation 2344 /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const 2345 /// version of AttachedTransformation() always returns NULL. 2346 virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;} 2347 2348 /// \brief Returns the object immediately attached to this object 2349 /// \return the attached transformation 2350 /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const 2351 /// version of AttachedTransformation() always returns NULL. 2352 virtual const BufferedTransformation *AttachedTransformation() const 2353 {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();} 2354 2355 /// \brief Delete the current attachment chain and attach a new one 2356 /// \param newAttachment the new BufferedTransformation to attach 2357 /// \throw NotImplemented 2358 /// \details Detach() deletes the current attachment chain and replace it with an optional newAttachment 2359 /// \details If a derived class does not override Detach(), then the base class throws 2360 /// NotImplemented. 2361 virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) { 2362 CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable()); 2363 throw NotImplemented("BufferedTransformation: this object is not attachable"); 2364 } 2365 2366 /// \brief Add newAttachment to the end of attachment chain 2367 /// \param newAttachment the attachment to add to the end of the chain 2368 virtual void Attach(BufferedTransformation *newAttachment); 2369 //@} 2370 2371 protected: 2372 /// \brief Decrements the propagation count while clamping at 0 2373 /// \return the decremented propagation or 0 2374 static int DecrementPropagation(int propagation) 2375 {return propagation != 0 ? propagation - 1 : 0;} 2376 2377 private: 2378 // for ChannelPutWord16, ChannelPutWord32 and ChannelPutWord64, 2379 // to ensure the buffer isn't deallocated before non-blocking 2380 // operation completes 2381 byte m_buf[8]; 2382 }; 2383 2384 /// \brief An input discarding BufferedTransformation 2385 /// \return a reference to a BufferedTransformation object that discards all input 2386 CRYPTOPP_DLL BufferedTransformation & TheBitBucket(); 2387 2388 /// \brief Interface for crypto material 2389 /// \details CryptoMaterial() is an interface for crypto material, such as 2390 /// public keys, private keys and crypto parameters. Derived classes generally 2391 /// do not offer public methods such as GenerateRandom() and 2392 /// GenerateRandomWithKeySize(). 2393 /// \sa GeneratableCryptoMaterial() 2394 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs 2395 { 2396 public: 2397 /// Exception thrown when invalid crypto material is detected 2398 class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat 2399 { 2400 public: 2401 explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {} 2402 }; 2403 2404 virtual ~CryptoMaterial() {} 2405 2406 /// \brief Assign values to this object 2407 /// \details This function can be used to create a public key from a private key. 2408 virtual void AssignFrom(const NameValuePairs &source) =0; 2409 2410 /// \brief Check this object for errors 2411 /// \param rng a RandomNumberGenerator for objects which use randomized testing 2412 /// \param level the level of thoroughness 2413 /// \return true if the tests succeed, false otherwise 2414 /// \details There are four levels of thoroughness: 2415 /// <ul> 2416 /// <li>0 - using this object won't cause a crash or exception 2417 /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly 2418 /// <li>2 - ensure this object will function correctly, and perform reasonable security checks 2419 /// <li>3 - perform reasonable security checks, and do checks that may take a long time 2420 /// </ul> 2421 /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0. 2422 /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended. 2423 /// \sa ThrowIfInvalid() 2424 virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0; 2425 2426 /// \brief Check this object for errors 2427 /// \param rng a RandomNumberGenerator for objects which use randomized testing 2428 /// \param level the level of thoroughness 2429 /// \throw InvalidMaterial 2430 /// \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial() if validation fails. 2431 /// \sa Validate() 2432 virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const 2433 {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");} 2434 2435 /// \brief Saves a key to a BufferedTransformation 2436 /// \param bt the destination BufferedTransformation 2437 /// \throw NotImplemented 2438 /// \details Save() writes the material to a BufferedTransformation. 2439 /// \details If the material is a key, then the key is written with ASN.1 DER encoding. The key 2440 /// includes an object identifier with an algorithm id, like a subjectPublicKeyInfo. 2441 /// \details A "raw" key without the "key info" can be saved using a key's DEREncode() method. 2442 /// \details If a derived class does not override Save(), then the base class throws 2443 /// NotImplemented(). 2444 virtual void Save(BufferedTransformation &bt) const 2445 {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");} 2446 2447 /// \brief Loads a key from a BufferedTransformation 2448 /// \param bt the source BufferedTransformation 2449 /// \throw KeyingErr 2450 /// \details Load() attempts to read material from a BufferedTransformation. If the 2451 /// material is a key that was generated outside the library, then the following 2452 /// usually applies: 2453 /// <ul> 2454 /// <li>the key should be ASN.1 BER encoded 2455 /// <li>the key should be a "key info" 2456 /// </ul> 2457 /// \details "key info" means the key should have an object identifier with an algorithm id, 2458 /// like a subjectPublicKeyInfo. 2459 /// \details To read a "raw" key without the "key info", then call the key's BERDecode() method. 2460 /// \note Load() generally does not check that the key is valid. Call Validate(), if needed. 2461 virtual void Load(BufferedTransformation &bt) 2462 {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");} 2463 2464 /// \brief Determines whether the object supports precomputation 2465 /// \return true if the object supports precomputation, false otherwise 2466 /// \sa Precompute() 2467 virtual bool SupportsPrecomputation() const {return false;} 2468 2469 /// \brief Perform precomputation 2470 /// \param precomputationStorage the suggested number of objects for the precompute table 2471 /// \throw NotImplemented 2472 /// \details The exact semantics of Precompute() varies, but it typically means calculate 2473 /// a table of n objects that can be used later to speed up computation. 2474 /// \details If a derived class does not override Precompute(), then the base class throws 2475 /// NotImplemented. 2476 /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation() 2477 virtual void Precompute(unsigned int precomputationStorage) { 2478 CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation()); 2479 throw NotImplemented("CryptoMaterial: this object does not support precomputation"); 2480 } 2481 2482 /// \brief Retrieve previously saved precomputation 2483 /// \param storedPrecomputation BufferedTransformation with the saved precomputation 2484 /// \throw NotImplemented 2485 /// \sa SupportsPrecomputation(), Precompute() 2486 virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation) 2487 {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} 2488 2489 /// \brief Save precomputation for later use 2490 /// \param storedPrecomputation BufferedTransformation to write the precomputation 2491 /// \throw NotImplemented 2492 /// \sa SupportsPrecomputation(), Precompute() 2493 virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const 2494 {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");} 2495 2496 /// \brief Perform a quick sanity check 2497 /// \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users. 2498 void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);} 2499 2500 #if defined(__SUNPRO_CC) 2501 // Sun Studio 11/CC 5.8 workaround: it generates incorrect code 2502 // when casting to an empty virtual base class. JW, 2018: It is 2503 // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable 2504 // it everywhere in case it affects SPARC (which we don't test). 2505 char m_sunCCworkaround; 2506 #endif 2507 }; 2508 2509 /// \brief Interface for crypto material 2510 /// \details GeneratableCryptoMaterial() is an interface for crypto material, 2511 /// such as private keys and crypto parameters. Derived classes offer public 2512 /// methods such as GenerateRandom() and GenerateRandomWithKeySize(). 2513 /// \sa CryptoMaterial() 2514 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial 2515 { 2516 public: 2517 virtual ~GeneratableCryptoMaterial() {} 2518 2519 /// \brief Generate a random key or crypto parameters 2520 /// \param rng a RandomNumberGenerator to produce keying material 2521 /// \param params additional initialization parameters 2522 /// \throw KeyingErr if a key can't be generated or algorithm parameters are invalid 2523 /// \details If a derived class does not override GenerateRandom(), then the base class throws 2524 /// NotImplemented. 2525 virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶ms = g_nullNameValuePairs) { 2526 CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params); 2527 throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation"); 2528 } 2529 2530 /// \brief Generate a random key or crypto parameters 2531 /// \param rng a RandomNumberGenerator to produce keying material 2532 /// \param keySize the size of the key, in bits 2533 /// \throw KeyingErr if a key can't be generated or algorithm parameters are invalid 2534 /// \details GenerateRandomWithKeySize calls GenerateRandom() with a NameValuePairs 2535 /// object with only "KeySize" 2536 void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize); 2537 }; 2538 2539 /// \brief Interface for public keys 2540 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial 2541 { 2542 }; 2543 2544 /// \brief Interface for private keys 2545 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial 2546 { 2547 }; 2548 2549 /// \brief Interface for crypto parameters 2550 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial 2551 { 2552 }; 2553 2554 /// \brief Interface for certificates 2555 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Certificate : virtual public CryptoMaterial 2556 { 2557 }; 2558 2559 /// \brief Interface for asymmetric algorithms 2560 /// \details BERDecode() and DEREncode() were removed under Issue 569 2561 /// and Commit 9b174e84de7a. Programs should use <tt>AccessMaterial().Load(bt)</tt> 2562 /// or <tt>GetMaterial().Save(bt)</tt> instead. 2563 /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/569">Issue 569</A> 2564 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm 2565 { 2566 public: 2567 virtual ~AsymmetricAlgorithm() {} 2568 2569 /// \brief Retrieves a reference to CryptoMaterial 2570 /// \return a reference to the crypto material 2571 virtual CryptoMaterial & AccessMaterial() =0; 2572 2573 /// \brief Retrieves a reference to CryptoMaterial 2574 /// \return a const reference to the crypto material 2575 virtual const CryptoMaterial & GetMaterial() const =0; 2576 2577 #if 0 2578 /// \brief Loads this object from a BufferedTransformation 2579 /// \param bt a BufferedTransformation object 2580 /// \details Use of BERDecode() changed to Load() at Issue 569. 2581 /// \deprecated for backwards compatibility, calls <tt>AccessMaterial().Load(bt)</tt> 2582 void BERDecode(BufferedTransformation &bt) 2583 {AccessMaterial().Load(bt);} 2584 2585 /// \brief Saves this object to a BufferedTransformation 2586 /// \param bt a BufferedTransformation object 2587 /// \details Use of DEREncode() changed to Save() at Issue 569. 2588 /// \deprecated for backwards compatibility, calls GetMaterial().Save(bt) 2589 void DEREncode(BufferedTransformation &bt) const 2590 {GetMaterial().Save(bt);} 2591 #endif 2592 }; 2593 2594 /// \brief Interface for asymmetric algorithms using public keys 2595 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm 2596 { 2597 public: 2598 virtual ~PublicKeyAlgorithm() {} 2599 2600 // VC60 workaround: no co-variant return type 2601 2602 /// \brief Retrieves a reference to a Public Key 2603 /// \return a reference to the public key 2604 CryptoMaterial & AccessMaterial() 2605 {return AccessPublicKey();} 2606 /// \brief Retrieves a reference to a Public Key 2607 /// \return a const reference the public key 2608 const CryptoMaterial & GetMaterial() const 2609 {return GetPublicKey();} 2610 2611 /// \brief Retrieves a reference to a Public Key 2612 /// \return a reference to the public key 2613 virtual PublicKey & AccessPublicKey() =0; 2614 /// \brief Retrieves a reference to a Public Key 2615 /// \return a const reference the public key 2616 virtual const PublicKey & GetPublicKey() const 2617 {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();} 2618 }; 2619 2620 /// \brief Interface for asymmetric algorithms using private keys 2621 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm 2622 { 2623 public: 2624 virtual ~PrivateKeyAlgorithm() {} 2625 2626 /// \brief Retrieves a reference to a Private Key 2627 /// \return a reference the private key 2628 CryptoMaterial & AccessMaterial() {return AccessPrivateKey();} 2629 /// \brief Retrieves a reference to a Private Key 2630 /// \return a const reference the private key 2631 const CryptoMaterial & GetMaterial() const {return GetPrivateKey();} 2632 2633 /// \brief Retrieves a reference to a Private Key 2634 /// \return a reference the private key 2635 virtual PrivateKey & AccessPrivateKey() =0; 2636 /// \brief Retrieves a reference to a Private Key 2637 /// \return a const reference the private key 2638 virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();} 2639 }; 2640 2641 /// \brief Interface for key agreement algorithms 2642 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm 2643 { 2644 public: 2645 virtual ~KeyAgreementAlgorithm() {} 2646 2647 /// \brief Retrieves a reference to Crypto Parameters 2648 /// \return a reference the crypto parameters 2649 CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();} 2650 /// \brief Retrieves a reference to Crypto Parameters 2651 /// \return a const reference the crypto parameters 2652 const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();} 2653 2654 /// \brief Retrieves a reference to Crypto Parameters 2655 /// \return a reference the crypto parameters 2656 virtual CryptoParameters & AccessCryptoParameters() =0; 2657 /// \brief Retrieves a reference to Crypto Parameters 2658 /// \return a const reference the crypto parameters 2659 virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();} 2660 }; 2661 2662 /// \brief Interface for public-key encryptors and decryptors 2663 /// \details This class provides an interface common to encryptors and decryptors 2664 /// for querying their plaintext and ciphertext lengths. 2665 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem 2666 { 2667 public: 2668 virtual ~PK_CryptoSystem() {} 2669 2670 /// \brief Provides the maximum length of plaintext for a given ciphertext length 2671 /// \return the maximum size of the plaintext, in bytes 2672 /// \details This function returns 0 if ciphertextLength is not valid (too long or too short). 2673 virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0; 2674 2675 /// \brief Calculate the length of ciphertext given length of plaintext 2676 /// \return the maximum size of the ciphertext, in bytes 2677 /// \details This function returns 0 if plaintextLength is not valid (too long). 2678 virtual size_t CiphertextLength(size_t plaintextLength) const =0; 2679 2680 /// \brief Determines whether this object supports the use of a named parameter 2681 /// \param name the name of the parameter 2682 /// \return true if the parameter name is supported, false otherwise 2683 /// \details Some possible parameter names: EncodingParameters(), KeyDerivationParameters() 2684 /// and others Parameters listed in argnames.h 2685 virtual bool ParameterSupported(const char *name) const =0; 2686 2687 /// \brief Provides the fixed ciphertext length, if one exists 2688 /// \return the fixed ciphertext length if one exists, otherwise 0 2689 /// \details "Fixed" here means length of ciphertext does not depend on length of plaintext. 2690 /// In this case, it usually does depend on the key length. 2691 virtual size_t FixedCiphertextLength() const {return 0;} 2692 2693 /// \brief Provides the maximum plaintext length given a fixed ciphertext length 2694 /// \return maximum plaintext length given the fixed ciphertext length, if one exists, 2695 /// otherwise return 0. 2696 /// \details FixedMaxPlaintextLength(0 returns the maximum plaintext length given the fixed ciphertext 2697 /// length, if one exists, otherwise return 0. 2698 virtual size_t FixedMaxPlaintextLength() const {return 0;} 2699 }; 2700 2701 /// \brief Interface for public-key encryptors 2702 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm 2703 { 2704 public: 2705 /// \brief Exception thrown when trying to encrypt plaintext of invalid length 2706 class CRYPTOPP_DLL InvalidPlaintextLength : public Exception 2707 { 2708 public: 2709 InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {} 2710 }; 2711 2712 /// \brief Encrypt a byte string 2713 /// \param rng a RandomNumberGenerator derived class 2714 /// \param plaintext the plaintext byte buffer 2715 /// \param plaintextLength the size of the plaintext byte buffer 2716 /// \param ciphertext a byte buffer to hold the encrypted string 2717 /// \param parameters a set of NameValuePairs to initialize this object 2718 /// \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large 2719 /// \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output 2720 /// byte buffer is large enough. 2721 /// \sa PK_Decryptor 2722 virtual void Encrypt(RandomNumberGenerator &rng, 2723 const byte *plaintext, size_t plaintextLength, 2724 byte *ciphertext, const NameValuePairs ¶meters = g_nullNameValuePairs) const =0; 2725 2726 /// \brief Create a new encryption filter 2727 /// \param rng a RandomNumberGenerator derived class 2728 /// \param attachment an attached transformation 2729 /// \param parameters a set of NameValuePairs to initialize this object 2730 /// \details \p attachment can be \p NULL. The caller is responsible for deleting the returned pointer. 2731 /// Encoding parameters should be passed in the "EP" channel. 2732 virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, 2733 BufferedTransformation *attachment=NULLPTR, const NameValuePairs ¶meters = g_nullNameValuePairs) const; 2734 }; 2735 2736 /// \brief Interface for public-key decryptors 2737 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm 2738 { 2739 public: 2740 virtual ~PK_Decryptor() {} 2741 2742 /// \brief Decrypt a byte string 2743 /// \param rng a RandomNumberGenerator derived class 2744 /// \param ciphertext the encrypted byte buffer 2745 /// \param ciphertextLength the size of the encrypted byte buffer 2746 /// \param plaintext a byte buffer to hold the decrypted string 2747 /// \param parameters a set of NameValuePairs to initialize this object 2748 /// \return the result of the decryption operation 2749 /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength 2750 /// is valid and holds the actual length of the plaintext recovered. The result is undefined 2751 /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength 2752 /// is undefined. 2753 /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output 2754 /// byte buffer is large enough 2755 /// \sa PK_Encryptor 2756 virtual DecodingResult Decrypt(RandomNumberGenerator &rng, 2757 const byte *ciphertext, size_t ciphertextLength, 2758 byte *plaintext, const NameValuePairs ¶meters = g_nullNameValuePairs) const =0; 2759 2760 /// \brief Create a new decryption filter 2761 /// \param rng a RandomNumberGenerator derived class 2762 /// \param attachment an attached transformation 2763 /// \param parameters a set of NameValuePairs to initialize this object 2764 /// \return the newly created decryption filter 2765 /// \note the caller is responsible for deleting the returned pointer 2766 virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, 2767 BufferedTransformation *attachment=NULLPTR, const NameValuePairs ¶meters = g_nullNameValuePairs) const; 2768 2769 /// \brief Decrypt a fixed size ciphertext 2770 /// \param rng a RandomNumberGenerator derived class 2771 /// \param ciphertext the encrypted byte buffer 2772 /// \param plaintext a byte buffer to hold the decrypted string 2773 /// \param parameters a set of NameValuePairs to initialize this object 2774 /// \return the result of the decryption operation 2775 /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength 2776 /// is valid and holds the actual length of the plaintext recovered. The result is undefined 2777 /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength 2778 /// is undefined. 2779 /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output 2780 /// byte buffer is large enough 2781 /// \sa PK_Encryptor 2782 DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs ¶meters = g_nullNameValuePairs) const 2783 {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);} 2784 }; 2785 2786 /// \brief Interface for public-key signers and verifiers 2787 /// \details This class provides an interface common to signers and verifiers for querying scheme properties 2788 /// \sa DL_SignatureSchemeBase, TF_SignatureSchemeBase, DL_SignerBase, TF_SignerBase 2789 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme 2790 { 2791 public: 2792 /// \brief Exception throw when the private or public key has a length that can't be used 2793 /// \details InvalidKeyLength() may be thrown by any function in this class if the private 2794 /// or public key has a length that can't be used 2795 class CRYPTOPP_DLL InvalidKeyLength : public Exception 2796 { 2797 public: 2798 InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {} 2799 }; 2800 2801 /// \brief Exception throw when the private or public key is too short to sign or verify 2802 /// \details KeyTooShort() may be thrown by any function in this class if the private or public 2803 /// key is too short to sign or verify anything 2804 class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength 2805 { 2806 public: 2807 KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {} 2808 }; 2809 2810 virtual ~PK_SignatureScheme() {} 2811 2812 /// \brief Provides the signature length if it only depends on the key 2813 /// \return the signature length if it only depends on the key, in bytes 2814 /// \details SignatureLength() returns the signature length if it only depends on the key, otherwise 0. 2815 virtual size_t SignatureLength() const =0; 2816 2817 /// \brief Provides the maximum signature length produced given the length of the recoverable message part 2818 /// \param recoverablePartLength the length of the recoverable message part, in bytes 2819 /// \return the maximum signature length produced for a given length of recoverable message part, in bytes 2820 /// \details MaxSignatureLength() returns the maximum signature length produced given the length of the 2821 /// recoverable message part. 2822 virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const 2823 {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();} 2824 2825 /// \brief Provides the length of longest message that can be recovered 2826 /// \return the length of longest message that can be recovered, in bytes 2827 /// \details MaxRecoverableLength() returns the length of longest message that can be recovered, or 0 if 2828 /// this signature scheme does not support message recovery. 2829 virtual size_t MaxRecoverableLength() const =0; 2830 2831 /// \brief Provides the length of longest message that can be recovered from a signature of given length 2832 /// \param signatureLength the length of the signature, in bytes 2833 /// \return the length of longest message that can be recovered from a signature of given length, in bytes 2834 /// \details MaxRecoverableLengthFromSignatureLength() returns the length of longest message that can be 2835 /// recovered from a signature of given length, or 0 if this signature scheme does not support message 2836 /// recovery. 2837 virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0; 2838 2839 /// \brief Determines whether a signature scheme requires a random number generator 2840 /// \return true if the signature scheme requires a RandomNumberGenerator() to sign 2841 /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take 2842 /// RandomNumberGenerator(). 2843 virtual bool IsProbabilistic() const =0; 2844 2845 /// \brief Determines whether the non-recoverable message part can be signed 2846 /// \return true if the non-recoverable message part can be signed 2847 virtual bool AllowNonrecoverablePart() const =0; 2848 2849 /// \brief Determines whether the signature must be input before the message 2850 /// \return true if the signature must be input before the message during verifcation 2851 /// \details if SignatureUpfront() returns true, then you must input the signature before the message 2852 /// during verification. Otherwise you can input the signature at anytime. 2853 virtual bool SignatureUpfront() const {return false;} 2854 2855 /// \brief Determines whether the recoverable part must be input before the non-recoverable part 2856 /// \return true if the recoverable part must be input before the non-recoverable part during signing 2857 /// \details RecoverablePartFirst() determines whether you must input the recoverable part before the 2858 /// non-recoverable part during signing 2859 virtual bool RecoverablePartFirst() const =0; 2860 }; 2861 2862 /// \brief Interface for accumulating messages to be signed or verified 2863 /// \details Only Update() should be called from the PK_MessageAccumulator() class. No other functions 2864 /// inherited from HashTransformation, like DigestSize() and TruncatedFinal(), should be called. 2865 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation 2866 { 2867 public: 2868 /// \warning DigestSize() should not be called on PK_MessageAccumulator 2869 unsigned int DigestSize() const 2870 {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");} 2871 2872 /// \warning TruncatedFinal() should not be called on PK_MessageAccumulator 2873 void TruncatedFinal(byte *digest, size_t digestSize) 2874 { 2875 CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize); 2876 throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called"); 2877 } 2878 }; 2879 2880 /// \brief Interface for public-key signers 2881 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm 2882 { 2883 public: 2884 virtual ~PK_Signer() {} 2885 2886 /// \brief Create a new HashTransformation to accumulate the message to be signed 2887 /// \param rng a RandomNumberGenerator derived class 2888 /// \return a pointer to a PK_MessageAccumulator 2889 /// \details NewSignatureAccumulator() can be used with all signing methods. Sign() will automatically delete the 2890 /// accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference. 2891 virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0; 2892 2893 /// \brief Input a recoverable message to an accumulator 2894 /// \param messageAccumulator a reference to a PK_MessageAccumulator 2895 /// \param recoverableMessage a pointer to the recoverable message part to be signed 2896 /// \param recoverableMessageLength the size of the recoverable message part 2897 virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0; 2898 2899 /// \brief Sign and delete the messageAccumulator 2900 /// \param rng a RandomNumberGenerator derived class 2901 /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class 2902 /// \param signature a block of bytes for the signature 2903 /// \return actual signature length 2904 /// \details Sign() deletes the messageAccumulator, even if an exception is thrown. 2905 /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt> 2906 virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const; 2907 2908 /// \brief Sign and restart messageAccumulator 2909 /// \param rng a RandomNumberGenerator derived class 2910 /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class 2911 /// \param signature a block of bytes for the signature 2912 /// \param restart flag indicating whether the messageAccumulator should be restarted 2913 /// \return actual signature length 2914 /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt> 2915 virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0; 2916 2917 /// \brief Sign a message 2918 /// \param rng a RandomNumberGenerator derived class 2919 /// \param message a pointer to the message 2920 /// \param messageLen the size of the message to be signed 2921 /// \param signature a block of bytes for the signature 2922 /// \return actual signature length 2923 /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt> 2924 virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const; 2925 2926 /// \brief Sign a recoverable message 2927 /// \param rng a RandomNumberGenerator derived class 2928 /// \param recoverableMessage a pointer to the recoverable message part to be signed 2929 /// \param recoverableMessageLength the size of the recoverable message part 2930 /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed 2931 /// \param nonrecoverableMessageLength the size of the non-recoverable message part 2932 /// \param signature a block of bytes for the signature 2933 /// \return actual signature length 2934 /// \pre <tt>COUNTOF(signature) == MaxSignatureLength(recoverableMessageLength)</tt> 2935 virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength, 2936 const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const; 2937 }; 2938 2939 /// \brief Interface for public-key signature verifiers 2940 /// \details The Recover* functions throw NotImplemented if the signature scheme does not support 2941 /// message recovery. 2942 /// \details The Verify* functions throw InvalidDataFormat if the scheme does support message 2943 /// recovery and the signature contains a non-empty recoverable message part. The 2944 /// Recover* functions should be used in that case. 2945 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm 2946 { 2947 public: 2948 virtual ~PK_Verifier() {} 2949 2950 /// \brief Create a new HashTransformation to accumulate the message to be verified 2951 /// \return a pointer to a PK_MessageAccumulator 2952 /// \details NewVerificationAccumulator() can be used with all verification methods. Verify() will automatically delete 2953 /// the accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference. 2954 virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0; 2955 2956 /// \brief Input signature into a message accumulator 2957 /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class 2958 /// \param signature the signature on the message 2959 /// \param signatureLength the size of the signature 2960 virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0; 2961 2962 /// \brief Check whether messageAccumulator contains a valid signature and message 2963 /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class 2964 /// \return true if the signature is valid, false otherwise 2965 /// \details Verify() deletes the messageAccumulator, even if an exception is thrown. 2966 virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const; 2967 2968 /// \brief Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator 2969 /// \param messageAccumulator a reference to a PK_MessageAccumulator derived class 2970 /// \return true if the signature is valid, false otherwise 2971 /// \details VerifyAndRestart() restarts the messageAccumulator 2972 virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0; 2973 2974 /// \brief Check whether input signature is a valid signature for input message 2975 /// \param message a pointer to the message to be verified 2976 /// \param messageLen the size of the message 2977 /// \param signature a pointer to the signature over the message 2978 /// \param signatureLen the size of the signature 2979 /// \return true if the signature is valid, false otherwise 2980 virtual bool VerifyMessage(const byte *message, size_t messageLen, 2981 const byte *signature, size_t signatureLen) const; 2982 2983 /// \brief Recover a message from its signature 2984 /// \param recoveredMessage a pointer to the recoverable message part to be verified 2985 /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class 2986 /// \return the result of the verification operation 2987 /// \details Recover() deletes the messageAccumulator, even if an exception is thrown. 2988 /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt> 2989 virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const; 2990 2991 /// \brief Recover a message from its signature 2992 /// \param recoveredMessage a pointer to the recoverable message part to be verified 2993 /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class 2994 /// \return the result of the verification operation 2995 /// \details RecoverAndRestart() restarts the messageAccumulator 2996 /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt> 2997 virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0; 2998 2999 /// \brief Recover a message from its signature 3000 /// \param recoveredMessage a pointer for the recovered message 3001 /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed 3002 /// \param nonrecoverableMessageLength the size of the non-recoverable message part 3003 /// \param signature the signature on the message 3004 /// \param signatureLength the size of the signature 3005 /// \return the result of the verification operation 3006 /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt> 3007 virtual DecodingResult RecoverMessage(byte *recoveredMessage, 3008 const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, 3009 const byte *signature, size_t signatureLength) const; 3010 }; 3011 3012 /// \brief Interface for domains of simple key agreement protocols 3013 /// \details A key agreement domain is a set of parameters that must be shared 3014 /// by two parties in a key agreement protocol, along with the algorithms 3015 /// for generating key pairs and deriving agreed values. 3016 /// \since Crypto++ 3.0 3017 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm 3018 { 3019 public: 3020 virtual ~SimpleKeyAgreementDomain() {} 3021 3022 /// \brief Provides the size of the agreed value 3023 /// \return size of agreed value produced in this domain 3024 virtual unsigned int AgreedValueLength() const =0; 3025 3026 /// \brief Provides the size of the private key 3027 /// \return size of private keys in this domain 3028 virtual unsigned int PrivateKeyLength() const =0; 3029 3030 /// \brief Provides the size of the public key 3031 /// \return size of public keys in this domain 3032 virtual unsigned int PublicKeyLength() const =0; 3033 3034 /// \brief Generate private key in this domain 3035 /// \param rng a RandomNumberGenerator derived class 3036 /// \param privateKey a byte buffer for the generated private key in this domain 3037 /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt> 3038 virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 3039 3040 /// \brief Generate a public key from a private key in this domain 3041 /// \param rng a RandomNumberGenerator derived class 3042 /// \param privateKey a byte buffer with the previously generated private key 3043 /// \param publicKey a byte buffer for the generated public key in this domain 3044 /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt> 3045 virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 3046 3047 /// \brief Generate a private/public key pair 3048 /// \param rng a RandomNumberGenerator derived class 3049 /// \param privateKey a byte buffer for the generated private key in this domain 3050 /// \param publicKey a byte buffer for the generated public key in this domain 3051 /// \details GenerateKeyPair() is equivalent to calling GeneratePrivateKey() and then GeneratePublicKey(). 3052 /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt> 3053 /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt> 3054 virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 3055 3056 /// \brief Derive agreed value 3057 /// \param agreedValue a byte buffer for the shared secret 3058 /// \param privateKey a byte buffer with your private key in this domain 3059 /// \param otherPublicKey a byte buffer with the other party's public key in this domain 3060 /// \param validateOtherPublicKey a flag indicating if the other party's public key should be validated 3061 /// \return true upon success, false in case of failure 3062 /// \details Agree() derives an agreed value from your private keys and couterparty's public keys. 3063 /// \details The other party's public key is validated by default. If you have previously validated the 3064 /// static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time. 3065 /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt> 3066 /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt> 3067 /// \pre <tt>COUNTOF(otherPublicKey) == PublicKeyLength()</tt> 3068 virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0; 3069 }; 3070 3071 /// \brief Interface for domains of authenticated key agreement protocols 3072 /// \details In an authenticated key agreement protocol, each party has two 3073 /// key pairs. The long-lived key pair is called the static key pair, 3074 /// and the short-lived key pair is called the ephemeral key pair. 3075 /// \since Crypto++ 3.0 3076 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm 3077 { 3078 public: 3079 virtual ~AuthenticatedKeyAgreementDomain() {} 3080 3081 /// \brief Provides the size of the agreed value 3082 /// \return size of agreed value produced in this domain 3083 virtual unsigned int AgreedValueLength() const =0; 3084 3085 /// \brief Provides the size of the static private key 3086 /// \return size of static private keys in this domain 3087 virtual unsigned int StaticPrivateKeyLength() const =0; 3088 3089 /// \brief Provides the size of the static public key 3090 /// \return size of static public keys in this domain 3091 virtual unsigned int StaticPublicKeyLength() const =0; 3092 3093 /// \brief Generate static private key in this domain 3094 /// \param rng a RandomNumberGenerator derived class 3095 /// \param privateKey a byte buffer for the generated private key in this domain 3096 /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt> 3097 virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 3098 3099 /// \brief Generate a static public key from a private key in this domain 3100 /// \param rng a RandomNumberGenerator derived class 3101 /// \param privateKey a byte buffer with the previously generated private key 3102 /// \param publicKey a byte buffer for the generated public key in this domain 3103 /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt> 3104 virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 3105 3106 /// \brief Generate a static private/public key pair 3107 /// \param rng a RandomNumberGenerator derived class 3108 /// \param privateKey a byte buffer for the generated private key in this domain 3109 /// \param publicKey a byte buffer for the generated public key in this domain 3110 /// \details GenerateStaticKeyPair() is equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey(). 3111 /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt> 3112 /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt> 3113 virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 3114 3115 /// \brief Provides the size of ephemeral private key 3116 /// \return the size of ephemeral private key in this domain 3117 virtual unsigned int EphemeralPrivateKeyLength() const =0; 3118 3119 /// \brief Provides the size of ephemeral public key 3120 /// \return the size of ephemeral public key in this domain 3121 virtual unsigned int EphemeralPublicKeyLength() const =0; 3122 3123 /// \brief Generate ephemeral private key 3124 /// \param rng a RandomNumberGenerator derived class 3125 /// \param privateKey a byte buffer for the generated private key in this domain 3126 /// \pre <tt>COUNTOF(privateKey) == PrivateEphemeralKeyLength()</tt> 3127 virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0; 3128 3129 /// \brief Generate ephemeral public key 3130 /// \param rng a RandomNumberGenerator derived class 3131 /// \param privateKey a byte buffer for the generated private key in this domain 3132 /// \param publicKey a byte buffer for the generated public key in this domain 3133 /// \pre <tt>COUNTOF(publicKey) == PublicEphemeralKeyLength()</tt> 3134 virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0; 3135 3136 /// \brief Generate private/public key pair 3137 /// \param rng a RandomNumberGenerator derived class 3138 /// \param privateKey a byte buffer for the generated private key in this domain 3139 /// \param publicKey a byte buffer for the generated public key in this domain 3140 /// \details GenerateEphemeralKeyPair() is equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() 3141 virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const; 3142 3143 /// \brief Derive agreed value 3144 /// \param agreedValue a byte buffer for the shared secret 3145 /// \param staticPrivateKey a byte buffer with your static private key in this domain 3146 /// \param ephemeralPrivateKey a byte buffer with your ephemeral private key in this domain 3147 /// \param staticOtherPublicKey a byte buffer with the other party's static public key in this domain 3148 /// \param ephemeralOtherPublicKey a byte buffer with the other party's ephemeral public key in this domain 3149 /// \param validateStaticOtherPublicKey a flag indicating if the other party's public key should be validated 3150 /// \return true upon success, false in case of failure 3151 /// \details Agree() derives an agreed value from your private keys and couterparty's public keys. 3152 /// \details The other party's ephemeral public key is validated by default. If you have previously validated 3153 /// the static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time. 3154 /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt> 3155 /// \pre <tt>COUNTOF(staticPrivateKey) == StaticPrivateKeyLength()</tt> 3156 /// \pre <tt>COUNTOF(ephemeralPrivateKey) == EphemeralPrivateKeyLength()</tt> 3157 /// \pre <tt>COUNTOF(staticOtherPublicKey) == StaticPublicKeyLength()</tt> 3158 /// \pre <tt>COUNTOF(ephemeralOtherPublicKey) == EphemeralPublicKeyLength()</tt> 3159 virtual bool Agree(byte *agreedValue, 3160 const byte *staticPrivateKey, const byte *ephemeralPrivateKey, 3161 const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey, 3162 bool validateStaticOtherPublicKey=true) const =0; 3163 }; 3164 3165 // interface for password authenticated key agreement protocols, not implemented yet 3166 #if 0 3167 /// \brief Interface for protocol sessions 3168 /*! The methods should be called in the following order: 3169 3170 InitializeSession(rng, parameters); // or call initialize method in derived class 3171 while (true) 3172 { 3173 if (OutgoingMessageAvailable()) 3174 { 3175 length = GetOutgoingMessageLength(); 3176 GetOutgoingMessage(message); 3177 ; // send outgoing message 3178 } 3179 3180 if (LastMessageProcessed()) 3181 break; 3182 3183 ; // receive incoming message 3184 ProcessIncomingMessage(message); 3185 } 3186 ; // call methods in derived class to obtain result of protocol session 3187 */ 3188 class ProtocolSession 3189 { 3190 public: 3191 /// Exception thrown when an invalid protocol message is processed 3192 class ProtocolError : public Exception 3193 { 3194 public: 3195 ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {} 3196 }; 3197 3198 /// Exception thrown when a function is called unexpectedly 3199 /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */ 3200 class UnexpectedMethodCall : public Exception 3201 { 3202 public: 3203 UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {} 3204 }; 3205 3206 virtual ~ProtocolSession() {} 3207 3208 ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {} 3209 3210 virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs ¶meters) =0; 3211 3212 bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;} 3213 void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;} 3214 3215 bool HasValidState() const {return m_validState;} 3216 3217 virtual bool OutgoingMessageAvailable() const =0; 3218 virtual unsigned int GetOutgoingMessageLength() const =0; 3219 virtual void GetOutgoingMessage(byte *message) =0; 3220 3221 virtual bool LastMessageProcessed() const =0; 3222 virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0; 3223 3224 protected: 3225 void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const; 3226 void CheckAndHandleInvalidState() const; 3227 void SetValidState(bool valid) {m_validState = valid;} 3228 3229 RandomNumberGenerator *m_rng; 3230 3231 private: 3232 bool m_throwOnProtocolError, m_validState; 3233 }; 3234 3235 class KeyAgreementSession : public ProtocolSession 3236 { 3237 public: 3238 virtual ~KeyAgreementSession() {} 3239 3240 virtual unsigned int GetAgreedValueLength() const =0; 3241 virtual void GetAgreedValue(byte *agreedValue) const =0; 3242 }; 3243 3244 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession 3245 { 3246 public: 3247 virtual ~PasswordAuthenticatedKeyAgreementSession() {} 3248 3249 void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng, 3250 const byte *myId, unsigned int myIdLength, 3251 const byte *counterPartyId, unsigned int counterPartyIdLength, 3252 const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength); 3253 }; 3254 3255 /// \brief Password based key agreement domain 3256 /// \since Crypto++ 3.0 3257 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm 3258 { 3259 public: 3260 virtual ~PasswordAuthenticatedKeyAgreementDomain() {} 3261 3262 /// return whether the domain parameters stored in this object are valid 3263 virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const 3264 {return GetCryptoParameters().Validate(rng, 2);} 3265 3266 virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0; 3267 virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0; 3268 3269 enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8}; 3270 3271 virtual bool IsValidRole(unsigned int role) =0; 3272 virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0; 3273 }; 3274 #endif 3275 3276 /// \brief Exception thrown when an ASN.1 BER decoing error is encountered 3277 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument 3278 { 3279 public: 3280 BERDecodeErr() : InvalidArgument("BER decode error") {} 3281 BERDecodeErr(const std::string &s) : InvalidArgument(s) {} 3282 }; 3283 3284 /// \brief Interface for encoding and decoding ASN1 objects 3285 /// \details Each class that derives from ASN1Object should provide a serialization format 3286 /// that controls subobject layout. Most of the time the serialization format is 3287 /// taken from a standard, like P1363 or an RFC. 3288 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object 3289 { 3290 public: 3291 virtual ~ASN1Object() {} 3292 3293 /// \brief Decode this object from a BufferedTransformation 3294 /// \param bt BufferedTransformation object 3295 /// \details Uses Basic Encoding Rules (BER) 3296 virtual void BERDecode(BufferedTransformation &bt) =0; 3297 3298 /// \brief Encode this object into a BufferedTransformation 3299 /// \param bt BufferedTransformation object 3300 /// \details Uses Distinguished Encoding Rules (DER) 3301 virtual void DEREncode(BufferedTransformation &bt) const =0; 3302 3303 /// \brief Encode this object into a BufferedTransformation 3304 /// \param bt BufferedTransformation object 3305 /// \details Uses Basic Encoding Rules (BER). 3306 /// \details This may be useful if DEREncode() would be too inefficient. 3307 virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);} 3308 }; 3309 3310 /// \brief Specifies the build-time version of the library 3311 /// \return integer representing the build-time version 3312 /// \details LibraryVersion can help detect inadvertent mixing and matching of library 3313 /// versions. When using Crypto++ distributed by a third party, LibraryVersion() 3314 /// records the version of the shared object that was built by the third party. 3315 /// The LibraryVersion() record resides in <tt>cryptlib.o</tt> on Unix compatibles 3316 /// and <tt>cryptlib.obj</tt> on Windows. It does not change when an app links 3317 /// to the library. 3318 /// \details LibraryVersion() is declared with C linkage (<tt>extern "C"</tt>) within the 3319 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then 3320 /// the library version is 5.7 or above. If it is missing, then the library version is 3321 /// 5.6.5 or below. 3322 /// \details The function could be used as shown below. 3323 /// <pre> if (LibraryVersion() != HeaderVersion()) 3324 /// { 3325 /// cout << "Potential version mismatch" << endl; 3326 /// 3327 /// const int lmaj = (LibraryVersion() / 100U) % 10; 3328 /// const int lmin = (LibraryVersion() / 10U) % 10; 3329 /// const int hmaj = (HeaderVersion() / 100U) % 10; 3330 /// const int hmin = (HeaderVersion() / 10U) % 10; 3331 /// 3332 /// if(lmaj != hmaj) 3333 /// cout << "Major version mismatch" << endl; 3334 /// else if(lmin != hmin) 3335 /// cout << "Minor version mismatch" << endl; 3336 /// } 3337 /// </pre> 3338 /// \sa HeaderVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>. 3339 /// \since Crypto++ 6.0 3340 extern "C" { 3341 int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT); 3342 } // C linkage 3343 3344 /// \brief Specifies the runtime version of the library 3345 /// \return integer representing the runtime version 3346 /// \details HeaderVersion() can help detect inadvertent mixing and matching of library 3347 /// versions. When using Crypto++ distributed by a third party, HeaderVersion() 3348 /// records the version of the headers used by the app when the app is compiled. 3349 /// \details HeaderVersion() is declared with C linkage (<tt>extern "C"</tt>) within the 3350 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then 3351 /// the library version is 5.7 or above. If it is missing, then the library version is 3352 /// 5.6.5 or below. 3353 /// \details The function could be used as shown below. 3354 /// <pre> if (LibraryVersion() != HeaderVersion()) 3355 /// { 3356 /// cout << "Potential version mismatch" << endl; 3357 /// 3358 /// const int lmaj = (LibraryVersion() / 100U) % 10; 3359 /// const int lmin = (LibraryVersion() / 10U) % 10; 3360 /// const int hmaj = (HeaderVersion() / 100U) % 10; 3361 /// const int hmin = (HeaderVersion() / 10U) % 10; 3362 /// 3363 /// if(lmaj != hmaj) 3364 /// cout << "Major version mismatch" << endl; 3365 /// else if(lmin != hmin) 3366 /// cout << "Minor version mismatch" << endl; 3367 /// } 3368 /// </pre> 3369 /// \sa LibraryVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>. 3370 /// \since Crypto++ 6.0 3371 extern "C" { 3372 inline int HeaderVersion() 3373 { 3374 return CRYPTOPP_VERSION; 3375 } 3376 } // C linkage 3377 3378 NAMESPACE_END 3379 3380 #if CRYPTOPP_MSC_VERSION 3381 # pragma warning(pop) 3382 #endif 3383 3384 #endif
[ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |