Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2667 lines
131 KiB

  1. // cryptlib.h - written and placed in the public domain by Wei Dai
  2. //! \file cryptlib.h
  3. //! \brief Abstract base classes that provide a uniform interface to this library.
  4. /*! \mainpage Crypto++ Library 5.6.3 API Reference
  5. <dl>
  6. <dt>Abstract Base Classes<dd>
  7. cryptlib.h
  8. <dt>Authenticated Encryption Modes<dd>
  9. CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)"
  10. <dt>Block Ciphers<dd>
  11. \ref Rijndael "AES", Weak::ARC4, Blowfish, BTEA, Camellia, CAST128, CAST256, DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES",
  12. \ref DES_XEX3 "DESX", GOST, IDEA, \ref LR "Luby-Rackoff", MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent,
  13. \ref SHACAL2 "SHACAL-2", SHARK, SKIPJACK,
  14. Square, TEA, \ref ThreeWay "3-Way", Twofish, XTEA
  15. <dt>Stream Ciphers<dd>
  16. \ref Panama "Panama-LE", \ref Panama "Panama-BE", Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20
  17. <dt>Hash Functions<dd>
  18. SHA1, SHA224, SHA256, SHA384, SHA512, \ref SHA3 "SHA-3", Tiger, Whirlpool, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, Weak::MD2, Weak::MD4, Weak::MD5
  19. <dt>Non-Cryptographic Checksums<dd>
  20. CRC32, Adler32
  21. <dt>Message Authentication Codes<dd>
  22. VMAC, HMAC, CBC_MAC, CMAC, DMAC, TTMAC, \ref GCM "GCM (GMAC)"
  23. <dt>Random Number Generators<dd>
  24. NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG,
  25. \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)", RDRAND, RDSEED
  26. <dt>Key Derivation and Password-based Cryptography<dd>
  27. HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)", \ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)"
  28. <dt>Public Key Cryptosystems<dd>
  29. DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
  30. <dt>Public Key Signature Schemes<dd>
  31. DSA2, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, RabinSS, RWSS, ESIGN
  32. <dt>Key Agreement<dd>
  33. DH, DH2, MQV, ECDH, ECMQV, XTR_DH
  34. <dt>Algebraic Structures<dd>
  35. Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
  36. ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP
  37. <dt>Secret Sharing and Information Dispersal<dd>
  38. SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
  39. <dt>Compression<dd>
  40. Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
  41. <dt>Input Source Classes<dd>
  42. StringSource, ArraySource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource
  43. <dt>Output Sink Classes<dd>
  44. StringSinkTemplate, StringSink, ArraySink, FileSink, SocketSink, WindowsPipeSink, RandomNumberSink
  45. <dt>Filter Wrappers<dd>
  46. StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter
  47. <dt>Binary to Text Encoders and Decoders<dd>
  48. HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder, Base32Decoder
  49. <dt>Wrappers for OS features<dd>
  50. Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer
  51. <dt>FIPS 140 validated cryptography<dd>
  52. fips140.h
  53. </dl>
  54. In the DLL version of Crypto++, only the following implementation class are available.
  55. <dl>
  56. <dt>Block Ciphers<dd>
  57. AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK
  58. <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
  59. \ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>", \ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>"
  60. <dt>Hash Functions<dd>
  61. SHA1, SHA224, SHA256, SHA384, SHA512
  62. <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
  63. RSASS\<PKCS1v15, H\>, RSASS\<PSS, H\>, RSASS_ISO\<H\>, RWSS\<P1363_EMSA2, H\>, DSA, ECDSA\<ECP, H\>, ECDSA\<EC2N, H\>
  64. <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
  65. HMAC\<H\>, CBC_MAC\<DES_EDE2\>, CBC_MAC\<DES_EDE3\>, GCM\<AES\>
  66. <dt>Random Number Generators<dd>
  67. DefaultAutoSeededRNG (AutoSeededX917RNG\<AES\>)
  68. <dt>Key Agreement<dd>
  69. DH, DH2
  70. <dt>Public Key Cryptosystems<dd>
  71. RSAES\<OAEP\<SHA1\> \>
  72. </dl>
  73. <p>This reference manual is a work in progress. Some classes are lack detailed descriptions.
  74. <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
  75. <p>Thanks to Ryan Phillips for providing the Doxygen configuration file
  76. and getting us started on the manual.
  77. */
  78. #ifndef CRYPTOPP_CRYPTLIB_H
  79. #define CRYPTOPP_CRYPTLIB_H
  80. #include "config.h"
  81. #include "stdcpp.h"
  82. #if CRYPTOPP_MSC_VERSION
  83. # pragma warning(push)
  84. # pragma warning(disable: 4127 4189 4702)
  85. #endif
  86. NAMESPACE_BEGIN(CryptoPP)
  87. // forward declarations
  88. class Integer;
  89. class RandomNumberGenerator;
  90. class BufferedTransformation;
  91. //! \brief Specifies a direction for a cipher to operate
  92. enum CipherDir {ENCRYPTION, DECRYPTION};
  93. //! \brief Represents infinite time
  94. const unsigned long INFINITE_TIME = ULONG_MAX;
  95. // VC60 workaround: using enums as template parameters causes problems
  96. //! \brief Converts a typename to an enumerated value
  97. template <typename ENUM_TYPE, int VALUE>
  98. struct EnumToType
  99. {
  100. static ENUM_TYPE ToEnum() {return (ENUM_TYPE)VALUE;}
  101. };
  102. //! \brief Provides the byte ordering
  103. enum ByteOrder {LITTLE_ENDIAN_ORDER = 0, BIG_ENDIAN_ORDER = 1};
  104. //! \typedef Provides a constant for LittleEndian
  105. typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian;
  106. //! \typedef Provides a constant for BigEndian
  107. typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian;
  108. //! \class Exception
  109. //! \brief Base class for all exceptions thrown by Crypto++
  110. class CRYPTOPP_DLL Exception : public std::exception
  111. {
  112. public:
  113. //! error types
  114. enum ErrorType {
  115. //! \brief A method was called which was not implemented
  116. NOT_IMPLEMENTED,
  117. //! \brief An invalid argument was detected
  118. INVALID_ARGUMENT,
  119. //! \brief BufferedTransformation received a Flush(true) signal but can't flush buffers
  120. CANNOT_FLUSH,
  121. //! \brief Data integerity check, such as CRC or MAC, failed
  122. DATA_INTEGRITY_CHECK_FAILED,
  123. //! \brief Input data was received that did not conform to expected format
  124. INVALID_DATA_FORMAT,
  125. //! \brief Error reading from input device or writing to output device
  126. IO_ERROR,
  127. //! \brief Some other error occurred not belong to any of the above categories
  128. OTHER_ERROR
  129. };
  130. //! \brief Construct a new Exception
  131. explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
  132. virtual ~Exception() throw() {}
  133. //! \brief Retrieves a C-string describing the exception
  134. const char *what() const throw() {return (m_what.c_str());}
  135. //! \brief Retrieves a string describing the exception
  136. const std::string &GetWhat() const {return m_what;}
  137. //! \brief Sets the error string for the exception
  138. void SetWhat(const std::string &s) {m_what = s;}
  139. //! \brief Retrieves the error type for the exception
  140. ErrorType GetErrorType() const {return m_errorType;}
  141. //! \brief Sets the error type for the exceptions
  142. void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
  143. private:
  144. ErrorType m_errorType;
  145. std::string m_what;
  146. };
  147. //! \brief An invalid argument was detected
  148. class CRYPTOPP_DLL InvalidArgument : public Exception
  149. {
  150. public:
  151. explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
  152. };
  153. //! \brief Input data was received that did not conform to expected format
  154. class CRYPTOPP_DLL InvalidDataFormat : public Exception
  155. {
  156. public:
  157. explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
  158. };
  159. //! \brief A decryption filter encountered invalid ciphertext
  160. class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
  161. {
  162. public:
  163. explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
  164. };
  165. //! \brief A method was called which was not implemented
  166. class CRYPTOPP_DLL NotImplemented : public Exception
  167. {
  168. public:
  169. explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
  170. };
  171. //! \brief Flush(true) was called but it can't completely flush its buffers
  172. class CRYPTOPP_DLL CannotFlush : public Exception
  173. {
  174. public:
  175. explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
  176. };
  177. //! \brief The operating system reported an error
  178. class CRYPTOPP_DLL OS_Error : public Exception
  179. {
  180. public:
  181. OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
  182. : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
  183. ~OS_Error() throw() {}
  184. //! \brief Retrieve the operating system API that reported the error
  185. const std::string & GetOperation() const {return m_operation;}
  186. //! \brief Retrieve the error code returned by the operating system
  187. int GetErrorCode() const {return m_errorCode;}
  188. protected:
  189. std::string m_operation;
  190. int m_errorCode;
  191. };
  192. //! \class DecodingResult
  193. //! \brief Returns a decoding results
  194. struct CRYPTOPP_DLL DecodingResult
  195. {
  196. //! \brief Constructs a DecodingResult
  197. //! \details isValidCoding is initialized to false and messageLength is initialized to 0.
  198. explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
  199. //! \brief Constructs a DecodingResult
  200. //! \param len the message length
  201. //! \details isValidCoding is initialized to true.
  202. explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
  203. //! \brief Compare two DecodingResult
  204. //! \param rhs the other DecodingResult
  205. //! \returns true if both isValidCoding and messageLength are equal, false otherwise
  206. bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
  207. //! \brief Compare two DecodingResult
  208. //! \param rhs the other DecodingResult
  209. //! \returns true if either isValidCoding or messageLength is \a not equal, false otherwise
  210. //! \details Returns <tt>!operator==(rhs)</tt>.
  211. bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
  212. //! \brief Flag to indicate the decoding is valid
  213. bool isValidCoding;
  214. //! \brief Recovered message length if isValidCoding is true, undefined otherwise
  215. size_t messageLength;
  216. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  217. operator size_t() const {return isValidCoding ? messageLength : 0;}
  218. #endif
  219. };
  220. //! \class NameValuePairs
  221. //! \brief Interface for retrieving values given their names
  222. //! \details This class is used to safely pass a variable number of arbitrarily typed arguments to functions
  223. //! and to read values from keys and crypto parameters.
  224. //! \details To obtain an object that implements NameValuePairs for the purpose of parameter
  225. //! passing, use the MakeParameters() function.
  226. //! \details To get a value from NameValuePairs, you need to know the name and the type of the value.
  227. //! Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports.
  228. //! then look at the Name namespace documentation to see what the type of each value is, or
  229. //! alternatively, call GetIntValue() with the value name, and if the type is not int, a
  230. //! ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object.
  231. class CRYPTOPP_NO_VTABLE NameValuePairs
  232. {
  233. public:
  234. virtual ~NameValuePairs() {}
  235. //! \class ValueTypeMismatch
  236. //! \brief Thrown when an unexpected type is encountered
  237. //! \details Exception thrown when trying to retrieve a value using a different type than expected
  238. class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
  239. {
  240. public:
  241. //! \brief Construct a ValueTypeMismatch
  242. //! \param name the name of the value
  243. //! \param stored the \a actual type of the value stored
  244. //! \param retrieving the \a presumed type of the value retrieved
  245. ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
  246. : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
  247. , m_stored(stored), m_retrieving(retrieving) {}
  248. //! \brief Provides the stored type
  249. //! \returns the C++ mangled name of the type
  250. const std::type_info & GetStoredTypeInfo() const {return m_stored;}
  251. //! \brief Provides the retrieveing type
  252. //! \returns the C++ mangled name of the type
  253. const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
  254. private:
  255. const std::type_info &m_stored;
  256. const std::type_info &m_retrieving;
  257. };
  258. //! \brief Get a copy of this object or subobject
  259. //! \tparam T class or type
  260. //! \param object reference to a variable that receives the value
  261. template <class T>
  262. bool GetThisObject(T &object) const
  263. {
  264. return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
  265. }
  266. //! \brief Get a pointer to this object
  267. //! \tparam T class or type
  268. //! \param ptr reference to a pointer to a variable that receives the value
  269. template <class T>
  270. bool GetThisPointer(T *&ptr) const
  271. {
  272. return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr);
  273. }
  274. //! \brief Get a named value
  275. //! \tparam T class or type
  276. //! \param name the name of the object or value to retrieve
  277. //! \param value reference to a variable that receives the value
  278. //! \returns true if the value was retrieved, false otherwise
  279. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  280. //! GetRequiredParameter() and GetRequiredIntParameter()
  281. template <class T>
  282. bool GetValue(const char *name, T &value) const
  283. {
  284. return GetVoidValue(name, typeid(T), &value);
  285. }
  286. //! \brief Get a named value
  287. //! \tparam T class or type
  288. //! \param name the name of the object or value to retrieve
  289. //! \param defaultValue the default value of the class or type if it does not exist
  290. //! \returns the object or value
  291. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  292. //! GetRequiredParameter() and GetRequiredIntParameter()
  293. template <class T>
  294. T GetValueWithDefault(const char *name, T defaultValue) const
  295. {
  296. T value;
  297. bool result = GetValue(name, value);
  298. // No assert... this recovers from failure
  299. if (result) {return value;}
  300. return defaultValue;
  301. }
  302. //! \brief Get a list of value names that can be retrieved
  303. //! \returns a list of names available to retrieve
  304. //! \details the items in the list are delimited with a colon.
  305. CRYPTOPP_DLL std::string GetValueNames() const
  306. {std::string result; GetValue("ValueNames", result); return result;}
  307. //! \brief Get a named value with type int
  308. //! \param name the name of the value to retrieve
  309. //! \param value the value retrieved upon success
  310. //! \returns true if an int value was retrieved, false otherwise
  311. //! \details GetIntValue() is used to ensure we don't accidentally try to get an
  312. //! unsigned int or some other type when we mean int (which is the most common case)
  313. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  314. //! GetRequiredParameter() and GetRequiredIntParameter()
  315. CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
  316. {return GetValue(name, value);}
  317. //! \brief Get a named value with type int, with default
  318. //! \param name the name of the value to retrieve
  319. //! \param defaultValue the default value if the name does not exist
  320. //! \returns the value retrieved on success or the default value
  321. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  322. //! GetRequiredParameter() and GetRequiredIntParameter()
  323. CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
  324. {return GetValueWithDefault(name, defaultValue);}
  325. //! \brief Ensures an expected name and type is present
  326. //! \param name the name of the value
  327. //! \param stored the type that was stored for the name
  328. //! \param retrieving the type that is being retrieved for the name
  329. //! \throws ValueTypeMismatch
  330. //! \details ThrowIfTypeMismatch() effectively performs a type safety check.
  331. //! stored and retrieving are C++ mangled names for the type.
  332. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  333. //! GetRequiredParameter() and GetRequiredIntParameter()
  334. CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
  335. {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
  336. //! \brief Retrieves a required name/value pair
  337. //! \tparam T class or type
  338. //! \param className the name of the class
  339. //! \param name the name of the value
  340. //! \param value reference to a variable to receive the value
  341. //! \throws InvalidArgument
  342. //! \details GetRequiredParameter() throws InvalidArgument if the name
  343. //! is not present or not of the expected type T.
  344. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  345. //! GetRequiredParameter() and GetRequiredIntParameter()
  346. template <class T>
  347. void GetRequiredParameter(const char *className, const char *name, T &value) const
  348. {
  349. if (!GetValue(name, value))
  350. throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
  351. }
  352. //! \brief Retrieves a required name/value pair
  353. //! \param className the name of the class
  354. //! \param name the name of the value
  355. //! \param value reference to a variable to receive the value
  356. //! \throws InvalidArgument
  357. //! \details GetRequiredParameter() throws InvalidArgument if the name
  358. //! is not present or not of the expected type T.
  359. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  360. //! GetRequiredParameter() and GetRequiredIntParameter()
  361. CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
  362. {
  363. if (!GetIntValue(name, value))
  364. throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
  365. }
  366. //! \brief Get a named value
  367. //! \param name the name of the object or value to retrieve
  368. //! \param valueType reference to a variable that receives the value
  369. //! \param pValue void pointer to a variable that receives the value
  370. //! \returns true if the value was retrieved, false otherwise
  371. //! \details GetVoidValue() retrives the value of name if it exists.
  372. //! \note GetVoidValue() is an internal function and should be implemented
  373. //! by derived classes. Users should use one of the other functions instead.
  374. //! \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  375. //! GetRequiredParameter() and GetRequiredIntParameter()
  376. CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
  377. };
  378. #if CRYPTOPP_DOXYGEN_PROCESSING
  379. //! \brief Namespace containing value name definitions.
  380. //! \details Name is part of the CryptoPP namespace.
  381. //! \details The semantics of value names, types are:
  382. //! <pre>
  383. //! ThisObject:ClassName (ClassName, copy of this object or a subobject)
  384. //! ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
  385. //! </pre>
  386. DOCUMENTED_NAMESPACE_BEGIN(Name)
  387. // more names defined in argnames.h
  388. DOCUMENTED_NAMESPACE_END
  389. //! \brief Namespace containing weak and wounded algorithms.
  390. //! \details Weak is part of the CryptoPP namespace. Schemes and algorithms are moved into Weak
  391. //! when their security level is reduced to an unacceptable value by contemporary standards.
  392. DOCUMENTED_NAMESPACE_BEGIN(Weak)
  393. // weak and wounded algorithms
  394. DOCUMENTED_NAMESPACE_END
  395. #endif
  396. //! \brief An empty set of name-value pairs
  397. extern CRYPTOPP_DLL const NameValuePairs &g_nullNameValuePairs;
  398. // ********************************************************
  399. //! \class Clonable
  400. //! \brief Interface for cloning objects
  401. //! \note this is \a not implemented by most classes
  402. //! \sa ClonableImpl, NotCopyable
  403. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
  404. {
  405. public:
  406. virtual ~Clonable() {}
  407. //! \brief Copies this object
  408. //! \returns a copy of this object
  409. //! \throws NotImplemented
  410. //! \note this is \a not implemented by most classes
  411. //! \sa NotCopyable
  412. virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
  413. };
  414. //! \class Algorithm
  415. //! \brief Interface for all crypto algorithms
  416. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
  417. {
  418. public:
  419. //! \brief Interface for all crypto algorithms
  420. //! \param checkSelfTestStatus determines whether the object can proceed if the self
  421. //! tests have not been run or failed.
  422. //! \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
  423. //! this constructor throws SelfTestFailure if the self test hasn't been run or fails.
  424. //! \details FIPS 140-2 compliance is disabled by default. It is only used by certain
  425. //! versions of the library when the library is built as a DLL on Windows. Also see
  426. //! CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h.
  427. Algorithm(bool checkSelfTestStatus = true);
  428. //! \brief Provides the name of this algorithm
  429. //! \returns the standard algorithm name
  430. //! \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms
  431. //! do not have standard names yet. For example, there is no standard algorithm name for
  432. //! Shoup's ECIES.
  433. //! \note AlgorithmName is not universally implemented yet
  434. virtual std::string AlgorithmName() const {return "unknown";}
  435. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  436. virtual ~Algorithm() {}
  437. #endif
  438. };
  439. //! \class SimpleKeyingInterface
  440. //! Interface for algorithms that take byte strings as keys
  441. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
  442. {
  443. public:
  444. virtual ~SimpleKeyingInterface() {}
  445. //! \brief Returns smallest valid key length in bytes
  446. virtual size_t MinKeyLength() const =0;
  447. //! \brief Returns largest valid key length in bytes
  448. virtual size_t MaxKeyLength() const =0;
  449. //! \brief Returns default (recommended) key length in bytes
  450. virtual size_t DefaultKeyLength() const =0;
  451. //! \brief
  452. //! \returns the smallest valid key length in bytes that is greater than or equal to <tt>min(n, GetMaxKeyLength())</tt>
  453. virtual size_t GetValidKeyLength(size_t n) const =0;
  454. //! \brief Returns whether keylength is a valid key length
  455. //! \details Internally the function calls GetValidKeyLength()
  456. virtual bool IsValidKeyLength(size_t keylength) const
  457. {return keylength == GetValidKeyLength(keylength);}
  458. //! \brief Sets or reset the key of this object
  459. //! \param key the key to use when keying the object
  460. //! \param length the size of the key, in bytes
  461. //! \param params additional initialization parameters that cannot be passed
  462. //! directly through the constructor
  463. virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
  464. //! \brief Sets or reset the key of this object
  465. //! \param key the key to use when keying the object
  466. //! \param length the size of the key, in bytes
  467. //! \param rounds the number of rounds to apply the transformation function,
  468. //! if applicable
  469. //! \details SetKeyWithRounds calls SetKey with an NameValuePairs
  470. //! object that just specifies rounds. rounds is an integer parameter,
  471. //! and <tt>-1</tt> means use the default number of rounds.
  472. void SetKeyWithRounds(const byte *key, size_t length, int rounds);
  473. //! \brief Sets or reset the key of this object
  474. //! \param key the key to use when keying the object
  475. //! \param length the size of the key, in bytes
  476. //! \param iv the intiialization vector to use when keying the object
  477. //! \param ivLength the size of the iv, in bytes
  478. //! \details SetKeyWithIV calls SetKey with an NameValuePairs object
  479. //! that just specifies iv. iv is a byte buffer with size ivLength.
  480. void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
  481. //! \brief Sets or reset the key of this object
  482. //! \param key the key to use when keying the object
  483. //! \param length the size of the key, in bytes
  484. //! \param iv the intiialization vector to use when keying the object
  485. //! \details SetKeyWithIV calls SetKey with an NameValuePairs object
  486. //! that just specifies iv. iv is a byte buffer, and it must have
  487. //! a size IVSize.
  488. void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
  489. {SetKeyWithIV(key, length, iv, IVSize());}
  490. //! \brief Provides IV requirements as an enumerated value.
  491. enum IV_Requirement {
  492. //! \brief The IV must be unique
  493. UNIQUE_IV = 0,
  494. //! \brief The IV must be random
  495. RANDOM_IV,
  496. //! \brief The IV must be unpredictable
  497. UNPREDICTABLE_RANDOM_IV,
  498. //! \brief The IV is set by the object
  499. INTERNALLY_GENERATED_IV,
  500. //! \brief The object does not use an IV
  501. NOT_RESYNCHRONIZABLE
  502. };
  503. //! returns the minimal requirement for secure IVs
  504. virtual IV_Requirement IVRequirement() const =0;
  505. //! returns whether the object can be resynchronized (i.e. supports initialization vectors)
  506. /*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */
  507. bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
  508. //! returns whether the object can use random IVs (in addition to ones returned by GetNextIV)
  509. bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
  510. //! returns whether the object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV)
  511. bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
  512. //! returns whether the object can use structured IVs, for example a counter (in addition to ones returned by GetNextIV)
  513. bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
  514. //! \brief Returns length of the IV accepted by this object
  515. //! \details The default implementation throws NotImplemented
  516. virtual unsigned int IVSize() const
  517. {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
  518. //! returns default length of IVs accepted by this object
  519. unsigned int DefaultIVLength() const {return IVSize();}
  520. //! returns minimal length of IVs accepted by this object
  521. virtual unsigned int MinIVLength() const {return IVSize();}
  522. //! returns maximal length of IVs accepted by this object
  523. virtual unsigned int MaxIVLength() const {return IVSize();}
  524. //! resynchronize with an IV. ivLength=-1 means use IVSize()
  525. virtual void Resynchronize(const byte *iv, int ivLength=-1) {
  526. CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength);
  527. throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");
  528. }
  529. //! \brief Gets a secure IV for the next message
  530. //! \param rng a RandomNumberGenerator to produce keying material
  531. //! \param iv a block of bytes to receive the IV
  532. //! \details This method should be called after you finish encrypting one message and are ready
  533. //! to start the next one. After calling it, you must call SetKey() or Resynchronize()
  534. //! before using this object again.
  535. //! \details key must be at least IVSize() in length.
  536. //! \note This method is not implemented on decryption objects.
  537. virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
  538. protected:
  539. //! \brief Returns the base class Algorithm
  540. //! \returns the base class Algorithm
  541. virtual const Algorithm & GetAlgorithm() const =0;
  542. //! \brief Sets the key for this object without performing parameter validation
  543. //! \param key a byte buffer used to key the cipher
  544. //! \param length the length of the byte buffer
  545. //! \param params additional parameters passed as NameValuePairs
  546. //! \details key must be at least DEFAULT_KEYLENGTH in length.
  547. virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
  548. //! \brief Validates the key length
  549. //! \param length the size of the keying material, in bytes
  550. //! \throws InvalidKeyLength if the key length is invalid
  551. void ThrowIfInvalidKeyLength(size_t length);
  552. //! \brief Validates the object
  553. //! \throws InvalidArgument if the IV is present
  554. //! \details Internally, the default implementation calls IsResynchronizable() and throws
  555. //! InvalidArgument if the function returns true.
  556. //! \note called when no IV is passed
  557. void ThrowIfResynchronizable();
  558. //! \brief Validates the IV
  559. //! \param iv the IV with a length of IVSize, in bytes
  560. //! \throws InvalidArgument on failure
  561. //! \details Internally, the default implementation checks the iv. If iv is not NULL,
  562. //! then the function succeeds. If iv is NULL, then IVRequirement is checked against
  563. //! UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then
  564. //! then the function succeeds. Otherwise, an exception is thrown.
  565. void ThrowIfInvalidIV(const byte *iv);
  566. //! \brief Validates the IV length
  567. //! \param length the size of the IV, in bytes
  568. //! \throws InvalidArgument if the number of rounds are invalid
  569. size_t ThrowIfInvalidIVLength(int length);
  570. //! \brief retrieves and validates the IV
  571. //! \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter
  572. //! \param size the length of the IV, in bytes
  573. //! \returns a pointer to the first byte of the IV
  574. //! \throws InvalidArgument if the number of rounds are invalid
  575. const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
  576. //! \brief Validates the key length
  577. //! \param length the size of the keying material, in bytes
  578. inline void AssertValidKeyLength(size_t length) const
  579. {CRYPTOPP_UNUSED(length); assert(IsValidKeyLength(length));}
  580. };
  581. //! \brief Interface for the data processing part of block ciphers
  582. //! \details Classes derived from BlockTransformation are block ciphers
  583. //! in ECB mode (for example the DES::Encryption class), which are stateless.
  584. //! These classes should not be used directly, but only in combination with
  585. //! a mode class (see CipherModeDocumentation in modes.h).
  586. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
  587. {
  588. public:
  589. //! \brief Encrypt or decrypt a block
  590. //! \param inBlock the input message before processing
  591. //! \param outBlock the output message after processing
  592. //! \param xorBlock an optional XOR mask
  593. //! \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock.
  594. //! \details The size of the block is determined by the block cipher and its documentation. Use
  595. //! BLOCKSIZE at compile time, or BlockSize() at runtime.
  596. //! \note The message can be transformed in-place, or the buffers must \a not overlap
  597. //! \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
  598. virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
  599. //! \brief Encrypt or decrypt a block
  600. //! \param inBlock the input message before processing
  601. //! \param outBlock the output message after processing
  602. //! \details ProcessBlock encrypts or decrypts inBlock and write to outBlock.
  603. //! \details The size of the block is determined by the block cipher and its documentation.
  604. //! Use BLOCKSIZE at compile time, or BlockSize() at runtime.
  605. //! \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
  606. //! \note The message can be transformed in-place, or the buffers must \a not overlap
  607. void ProcessBlock(const byte *inBlock, byte *outBlock) const
  608. {ProcessAndXorBlock(inBlock, NULL, outBlock);}
  609. //! \brief Encrypt or decrypt a block in place
  610. //! \param inoutBlock the input message before processing
  611. //! \details ProcessBlock encrypts or decrypts inoutBlock in-place.
  612. //! \details The size of the block is determined by the block cipher and its documentation.
  613. //! Use BLOCKSIZE at compile time, or BlockSize() at runtime.
  614. //! \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
  615. void ProcessBlock(byte *inoutBlock) const
  616. {ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);}
  617. //! Provides the block size of the cipher
  618. //! \returns the block size of the cipher, in bytes
  619. virtual unsigned int BlockSize() const =0;
  620. //! \brief Provides input and output data alignment for optimal performance.
  621. //! \returns the input data alignment that provides optimal performance
  622. virtual unsigned int OptimalDataAlignment() const;
  623. //! returns true if this is a permutation (i.e. there is an inverse transformation)
  624. virtual bool IsPermutation() const {return true;}
  625. //! \brief Determines if the cipher is being operated in its forward direction
  626. //! \returns true if DIR is ENCRYPTION, false otherwise
  627. //! \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
  628. virtual bool IsForwardTransformation() const =0;
  629. //! \brief Determines the number of blocks that can be processed in parallel
  630. //! \return the number of blocks that can be processed in parallel, for bit-slicing implementations
  631. //! \details Bit-slicing is often used to improve throughput and minimize timing attacks.
  632. virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
  633. //! \brief Bit flags that control AdvancedProcessBlocks() behavior
  634. enum FlagsForAdvancedProcessBlocks {
  635. //! \brief inBlock is a counter
  636. BT_InBlockIsCounter=1,
  637. //! \brief should not modify block pointers
  638. BT_DontIncrementInOutPointers=2,
  639. //! \brief
  640. BT_XorInput=4,
  641. //! \brief perform the transformation in reverse
  642. BT_ReverseDirection=8,
  643. //! \brief
  644. BT_AllowParallel=16};
  645. //! \brief Encrypt and xor multiple blocks using additional flags
  646. //! \param inBlocks the input message before processing
  647. //! \param xorBlocks an optional XOR mask
  648. //! \param outBlocks the output message after processing
  649. //! \param length the size of the blocks, in bytes
  650. //! \param flags additional flags to control processing
  651. //! \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags.
  652. //! \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified.
  653. virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
  654. //! \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
  655. inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
  656. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  657. virtual ~BlockTransformation() {}
  658. #endif
  659. };
  660. //! \class StreamTransformation
  661. //! \brief Interface for the data processing portion of stream ciphers
  662. //! \sa StreamTransformationFilter()
  663. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
  664. {
  665. public:
  666. //! \brief Provides a reference to this object
  667. //! \returns A reference to this object
  668. //! \details Useful for passing a temporary object to a function that takes a non-const reference
  669. StreamTransformation& Ref() {return *this;}
  670. //! \brief Provides the mandatory block size of the cipher
  671. //! \returns The block size of the cipher if input must be processed in blocks, 1 otherwise
  672. virtual unsigned int MandatoryBlockSize() const {return 1;}
  673. //! \brief Provides the input block size most efficient for this cipher.
  674. //! \returns The input block size that is most efficient for the cipher
  675. //! \details The base class implemnetation returns MandatoryBlockSize().
  676. //! \note Optimal input length is
  677. //! <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>.
  678. virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
  679. //! \brief Provides the number of bytes used in the current block when processing at optimal block size.
  680. //! \returns the number of bytes used in the current block when processing at the optimal block size
  681. virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
  682. //! \brief Provides input and output data alignment for optimal performance.
  683. //! \returns the input data alignment that provides optimal performance
  684. virtual unsigned int OptimalDataAlignment() const;
  685. //! \brief Encrypt or decrypt an array of bytes
  686. //! \param outString the output byte buffer
  687. //! \param inString the input byte buffer
  688. //! \param length the size of the input and output byte buffers, in bytes
  689. //! \details Either <tt>inString == outString</tt>, or they must not overlap.
  690. virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
  691. //! \brief Encrypt or decrypt the last block of data
  692. //! \param outString the output byte buffer
  693. //! \param inString the input byte buffer
  694. //! \param length the size of the input and output byte buffers, in bytes
  695. //! ProcessLastBlock is used when the last block of data is special.
  696. //! Currently the only use of this function is CBC-CTS mode.
  697. virtual void ProcessLastBlock(byte *outString, const byte *inString, size_t length);
  698. //! returns the minimum size of the last block, 0 indicating the last block is not special
  699. virtual unsigned int MinLastBlockSize() const {return 0;}
  700. //! \brief Encrypt or decrypt a string of bytes
  701. //! \param inoutString the string to process
  702. //! \param length the size of the inoutString, in bytes
  703. //! \details Internally, the base class implementation calls ProcessData().
  704. inline void ProcessString(byte *inoutString, size_t length)
  705. {ProcessData(inoutString, inoutString, length);}
  706. //! \brief Encrypt or decrypt a string of bytes
  707. //! \param outString the output string to process
  708. //! \param inString the input string to process
  709. //! \param length the size of the input and output strings, in bytes
  710. //! \details Internally, the base class implementation calls ProcessData().
  711. inline void ProcessString(byte *outString, const byte *inString, size_t length)
  712. {ProcessData(outString, inString, length);}
  713. //! \brief Encrypt or decrypt a byte
  714. //! \param input the input byte to process
  715. //! \details Internally, the base class implementation calls ProcessData() with a size of 1.
  716. inline byte ProcessByte(byte input)
  717. {ProcessData(&input, &input, 1); return input;}
  718. //! \brief Determines whether the cipher supports random access
  719. //! \returns true if the cipher supports random access, false otherwise
  720. virtual bool IsRandomAccess() const =0;
  721. //! \brief Seek to an absolute position
  722. //! \param pos position to seek
  723. //! \throws NotImplemented
  724. //! \details The base class implementation throws NotImplemented. The function
  725. //! asserts IsRandomAccess() in debug builds.
  726. virtual void Seek(lword pos)
  727. {
  728. CRYPTOPP_UNUSED(pos);
  729. assert(!IsRandomAccess());
  730. throw NotImplemented("StreamTransformation: this object doesn't support random access");
  731. }
  732. //! \brief Determines whether the cipher is self-inverting
  733. //! \returns true if the cipher is self-inverting, false otherwise
  734. //! \details IsSelfInverting determines whether this transformation is
  735. //! self-inverting (e.g. xor with a keystream).
  736. virtual bool IsSelfInverting() const =0;
  737. //! \brief Determines if the cipher is being operated in its forward direction
  738. //! \returns true if DIR is ENCRYPTION, false otherwise
  739. //! \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
  740. virtual bool IsForwardTransformation() const =0;
  741. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  742. virtual ~StreamTransformation() {}
  743. #endif
  744. };
  745. //! \class HashTransformation
  746. //! \brief Interface for hash functions and data processing part of MACs
  747. //! \details HashTransformation objects are stateful. They are created in an initial state,
  748. //! change state as Update() is called, and return to the initial
  749. //! state when Final() is called. This interface allows a large message to
  750. //! be hashed in pieces by calling Update() on each piece followed by
  751. //! calling Final().
  752. //! \sa HashFilter(), HashVerificationFilter()
  753. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
  754. {
  755. public:
  756. //! \brief Provides a reference to this object
  757. //! \returns A reference to this object
  758. //! \details Useful for passing a temporary object to a function that takes a non-const reference
  759. HashTransformation& Ref() {return *this;}
  760. //! \brief Updates a hash with additional input
  761. //! \param input the additional input as a buffer
  762. //! \param length the size of the buffer, in bytes
  763. virtual void Update(const byte *input, size_t length) =0;
  764. //! \brief Request space which can be written into by the caller
  765. //! \param size the requested size of the buffer
  766. //! \details The purpose of this method is to help avoid extra memory allocations.
  767. //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
  768. //! size is the requested size of the buffer. When the call returns, size is the size of
  769. //! the array returned to the caller.
  770. //! \details The base class implementation sets size to 0 and returns NULL.
  771. //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
  772. virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULL;}
  773. //! \brief Computes the hash of the current message
  774. //! \param digest a pointer to the buffer to receive the hash
  775. //! \details digest must be equal to (or greater than) DigestSize(). Final() restarts the
  776. //! hash for a new message.
  777. virtual void Final(byte *digest)
  778. {TruncatedFinal(digest, DigestSize());}
  779. //! \brief Restart the hash
  780. //! \details Discards the current state, and restart for a new message
  781. virtual void Restart()
  782. {TruncatedFinal(NULL, 0);}
  783. //! Provides the digest size of the hash
  784. //! \returns the digest size of the hash.
  785. //! \details Calls to Final() require a buffer that is equal to (or greater than) DigestSize().
  786. virtual unsigned int DigestSize() const =0;
  787. //! Provides the tag size of the hash
  788. //! \returns the tag size of the hash.
  789. //! \details Same as DigestSize().
  790. unsigned int TagSize() const {return DigestSize();}
  791. //! \brief Provides the block size of the compression function
  792. //! \returns the block size of the compression function, in bytes
  793. //! \details BlockSize() will return 0 if the hash is not block based. For example,
  794. //! SHA3 is a recursive hash (not an iterative hash), and it does not have a block size.
  795. virtual unsigned int BlockSize() const {return 0;}
  796. //! \brief Provides the input block size most efficient for this hash.
  797. //! \returns The input block size that is most efficient for the cipher
  798. //! \details The base class implemnetation returns MandatoryBlockSize().
  799. //! \note Optimal input length is
  800. //! <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>.
  801. virtual unsigned int OptimalBlockSize() const {return 1;}
  802. //! \brief Provides input and output data alignment for optimal performance
  803. //! \returns the input data alignment that provides optimal performance
  804. virtual unsigned int OptimalDataAlignment() const;
  805. //! \brief Updates the hash with additional input and computes the hash of the current message
  806. //! \param digest a pointer to the buffer to receive the hash
  807. //! \param input the additional input as a buffer
  808. //! \param length the size of the buffer, in bytes
  809. //! \details Use this if your input is in one piece and you don't want to call Update()
  810. //! and Final() separately
  811. //! \details CalculateDigest() restarts the hash for the next nmessage.
  812. virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
  813. {Update(input, length); Final(digest);}
  814. //! \brief Verifies the hash of the current message
  815. //! \param digest a pointer to the buffer of an \a existing hash
  816. //! \returns \p true if the existing hash matches the computed hash, \p false otherwise
  817. //! \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
  818. //! \details Calls to Verify() require a buffer that is equal to (or greater than) DigestSize().
  819. //! \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
  820. //! a constant time comparison function. digestLength cannot exceed DigestSize().
  821. //! \details Verify() restarts the hash for the next nmessage.
  822. virtual bool Verify(const byte *digest)
  823. {return TruncatedVerify(digest, DigestSize());}
  824. //! \brief Updates the hash with additional input and verifies the hash of the current message
  825. //! \param digest a pointer to the buffer of an \a existing hash
  826. //! \param input the additional input as a buffer
  827. //! \param length the size of the buffer, in bytes
  828. //! \returns \p true if the existing hash matches the computed hash, \p false otherwise
  829. //! \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
  830. //! \details Use this if your input is in one piece and you don't want to call Update()
  831. //! and Verify() separately
  832. //! \details VerifyDigest() performs a bitwise compare on the buffers using VerifyBufsEqual(),
  833. //! which is a constant time comparison function. digestLength cannot exceed DigestSize().
  834. //! \details VerifyDigest() restarts the hash for the next nmessage.
  835. virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
  836. {Update(input, length); return Verify(digest);}
  837. //! \brief Computes the hash of the current message
  838. //! \param digest a pointer to the buffer to receive the hash
  839. //! \param digestSize the size of the truncated digest, in bytes
  840. //! \details TruncatedFinal() call Final() and then copies digestSize bytes to digest
  841. //! \details TruncatedFinal() restarts the hash for the next nmessage.
  842. virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
  843. //! \brief Updates the hash with additional input and computes the hash of the current message
  844. //! \param digest a pointer to the buffer to receive the hash
  845. //! \param digestSize the length of the truncated hash, in bytes
  846. //! \param input the additional input as a buffer
  847. //! \param length the size of the buffer, in bytes
  848. //! \details Use this if your input is in one piece and you don't want to call Update()
  849. //! and CalculateDigest() separately.
  850. //! \details CalculateTruncatedDigest() restarts the hash for the next nmessage.
  851. virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
  852. {Update(input, length); TruncatedFinal(digest, digestSize);}
  853. //! \brief Verifies the hash of the current message
  854. //! \param digest a pointer to the buffer of an \a existing hash
  855. //! \param digestLength the size of the truncated hash, in bytes
  856. //! \returns \p true if the existing hash matches the computed hash, \p false otherwise
  857. //! \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
  858. //! \details TruncatedVerify() is a truncated version of Verify(). It can operate on a
  859. //! buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
  860. //! \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
  861. //! a constant time comparison function. digestLength cannot exceed DigestSize().
  862. //! \details TruncatedVerify() restarts the hash for the next nmessage.
  863. virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
  864. //! \brief Updates the hash with additional input and verifies the hash of the current message
  865. //! \param digest a pointer to the buffer of an \a existing hash
  866. //! \param digestLength the size of the truncated hash, in bytes
  867. //! \param input the additional input as a buffer
  868. //! \param length the size of the buffer, in bytes
  869. //! \returns \p true if the existing hash matches the computed hash, \p false otherwise
  870. //! \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
  871. //! \details Use this if your input is in one piece and you don't want to call Update()
  872. //! and TruncatedVerify() separately.
  873. //! \details VerifyTruncatedDigest() is a truncated version of VerifyDigest(). It can operate
  874. //! on a buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
  875. //! \details VerifyTruncatedDigest() restarts the hash for the next nmessage.
  876. virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
  877. {Update(input, length); return TruncatedVerify(digest, digestLength);}
  878. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  879. virtual ~HashTransformation() {}
  880. #endif
  881. protected:
  882. //! \brief Exception thrown when the truncated digest size is greater than DigestSize()
  883. void ThrowIfInvalidTruncatedSize(size_t size) const;
  884. };
  885. typedef HashTransformation HashFunction;
  886. //! \brief Interface for one direction (encryption or decryption) of a block cipher
  887. /*! \note These objects usually should not be used directly. See BlockTransformation for more details. */
  888. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
  889. {
  890. protected:
  891. const Algorithm & GetAlgorithm() const {return *this;}
  892. };
  893. //! \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode
  894. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
  895. {
  896. protected:
  897. const Algorithm & GetAlgorithm() const {return *this;}
  898. };
  899. //! \brief Interface for message authentication codes
  900. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
  901. {
  902. protected:
  903. const Algorithm & GetAlgorithm() const {return *this;}
  904. };
  905. //! \brief Interface for one direction (encryption or decryption) of a stream cipher or block cipher mode with authentication
  906. /*! The StreamTransformation part of this interface is used to encrypt/decrypt the data, and the MessageAuthenticationCode part of this
  907. interface is used to input additional authenticated data (AAD, which is MAC'ed but not encrypted), and to generate/verify the MAC. */
  908. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
  909. {
  910. public:
  911. //! this indicates that a member function was called in the wrong state, for example trying to encrypt a message before having set the key or IV
  912. class BadState : public Exception
  913. {
  914. public:
  915. explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
  916. explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
  917. };
  918. //! the maximum length of AAD that can be input before the encrypted data
  919. virtual lword MaxHeaderLength() const =0;
  920. //! the maximum length of encrypted data
  921. virtual lword MaxMessageLength() const =0;
  922. //! the maximum length of AAD that can be input after the encrypted data
  923. virtual lword MaxFooterLength() const {return 0;}
  924. //! if this function returns true, SpecifyDataLengths() must be called before attempting to input data
  925. /*! This is the case for some schemes, such as CCM. */
  926. virtual bool NeedsPrespecifiedDataLengths() const {return false;}
  927. //! this function only needs to be called if NeedsPrespecifiedDataLengths() returns true
  928. void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
  929. //! encrypt and generate MAC in one call. will truncate MAC if macSize < TagSize()
  930. 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);
  931. //! decrypt and verify MAC in one call, returning true iff MAC is valid. will assume MAC is truncated if macLength < TagSize()
  932. virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macLength, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength);
  933. // redeclare this to avoid compiler ambiguity errors
  934. virtual std::string AlgorithmName() const =0;
  935. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  936. virtual ~AuthenticatedSymmetricCipher() {}
  937. #endif
  938. protected:
  939. const Algorithm & GetAlgorithm() const
  940. {return *static_cast<const MessageAuthenticationCode *>(this);}
  941. virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
  942. {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);}
  943. };
  944. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  945. typedef SymmetricCipher StreamCipher;
  946. #endif
  947. //! \class RandomNumberGenerator
  948. //! \brief Interface for random number generators
  949. //! \details The library provides a number of random number generators, from software based to hardware based generators.
  950. //! \details All generated values are uniformly distributed over the range specified.
  951. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
  952. {
  953. public:
  954. //! \brief Update RNG state with additional unpredictable values
  955. //! \param input the entropy to add to the generator
  956. //! \param length the size of the input buffer
  957. //! \throws NotImplemented
  958. //! \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy() to test for the
  959. //! ability to use additional entropy.
  960. //! \details If a derived class does not override IncorporateEntropy(), then the base class throws
  961. //! NotImplemented.
  962. virtual void IncorporateEntropy(const byte *input, size_t length)
  963. {
  964. CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
  965. throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
  966. }
  967. //! \brief Determines if a generator can accept additional entropy
  968. //! \returns true if IncorporateEntropy() is implemented
  969. virtual bool CanIncorporateEntropy() const {return false;}
  970. //! \brief Generate new random byte and return it
  971. //! \returns a random 8-bit byte
  972. //! \details Default implementation calls GenerateBlock() with one byte.
  973. //! \details All generated values are uniformly distributed over the range specified within the
  974. //! the contraints of a particular generator.
  975. virtual byte GenerateByte();
  976. //! \brief Generate new random bit and return it
  977. //! \returns a random bit
  978. //! \details The default implementation calls GenerateByte() and return its lowest bit.
  979. //! \details All generated values are uniformly distributed over the range specified within the
  980. //! the contraints of a particular generator.
  981. virtual unsigned int GenerateBit();
  982. //! \brief Generate a random 32 bit word in the range min to max, inclusive
  983. //! \param min the lower bound of the range
  984. //! \param max the upper bound of the range
  985. //! \returns a random 32-bit word
  986. //! \details The default implementation calls Crop() on the difference between max and
  987. //! min, and then returns the result added to min.
  988. //! \details All generated values are uniformly distributed over the range specified within the
  989. //! the contraints of a particular generator.
  990. virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL);
  991. //! \brief Generate random array of bytes
  992. //! \param output the byte buffer
  993. //! \param size the length of the buffer, in bytes
  994. //! \details All generated values are uniformly distributed over the range specified within the
  995. //! the contraints of a particular generator.
  996. //! \note A derived generator \a must override either GenerateBlock() or
  997. //! GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
  998. virtual void GenerateBlock(byte *output, size_t size);
  999. //! \brief Generate random bytes into a BufferedTransformation
  1000. //! \param target the BufferedTransformation object which receives the bytes
  1001. //! \param channel the channel on which the bytes should be pumped
  1002. //! \param length the number of bytes to generate
  1003. //! \details The default implementation calls GenerateBlock() and pumps the result into
  1004. //! the DEFAULT_CHANNEL of the target.
  1005. //! \details All generated values are uniformly distributed over the range specified within the
  1006. //! the contraints of a particular generator.
  1007. //! \note A derived generator \a must override either GenerateBlock() or
  1008. //! GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
  1009. virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
  1010. //! \brief Generate and discard n bytes
  1011. //! \param n the number of bytes to generate and discard
  1012. virtual void DiscardBytes(size_t n);
  1013. //! \brief Randomly shuffle the specified array
  1014. //! \param begin an iterator to the first element in the array
  1015. //! \param end an iterator beyond the last element in the array
  1016. //! \details The resulting permutation is uniformly distributed.
  1017. template <class IT> void Shuffle(IT begin, IT end)
  1018. {
  1019. // TODO: What happens if there are more than 2^32 elements?
  1020. for (; begin != end; ++begin)
  1021. std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1));
  1022. }
  1023. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1024. virtual ~RandomNumberGenerator() {}
  1025. #endif
  1026. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1027. byte GetByte() {return GenerateByte();}
  1028. unsigned int GetBit() {return GenerateBit();}
  1029. word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);}
  1030. word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);}
  1031. void GetBlock(byte *output, size_t size) {GenerateBlock(output, size);}
  1032. #endif
  1033. };
  1034. //! \brief Random Number Generator that does not produce random numbers
  1035. //! \returns reference that can be passed to functions that require a RandomNumberGenerator
  1036. //! \details NullRNG() returns a reference that can be passed to functions that require a
  1037. //! RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented
  1038. //! when a generation function is called.
  1039. //! \sa ClassNullRNG
  1040. CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
  1041. //! \class WaitObjectContainer
  1042. class WaitObjectContainer;
  1043. //! \class CallStack
  1044. class CallStack;
  1045. //! \brief Interface for objects that can be waited on.
  1046. class CRYPTOPP_NO_VTABLE Waitable
  1047. {
  1048. public:
  1049. virtual ~Waitable() {}
  1050. //! \brief Maximum number of wait objects that this object can return
  1051. virtual unsigned int GetMaxWaitObjectCount() const =0;
  1052. //! \brief Retrieves waitable objects
  1053. //! \param container the wait container to receive the references to the objects.
  1054. //! \param callStack CallStack object used to select waitable objects
  1055. //! \details GetWaitObjects is usually called in one of two ways. First, it can
  1056. //! be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
  1057. //! Second, if in an outer GetWaitObjects() method that itself takes a callStack
  1058. //! parameter, it can be called like
  1059. //! <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
  1060. virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
  1061. //! wait on this object
  1062. /*! same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container */
  1063. bool Wait(unsigned long milliseconds, CallStack const& callStack);
  1064. };
  1065. //! \brief Default channel for BufferedTransformation
  1066. //! \details DEFAULT_CHANNEL is equal to an empty string
  1067. // VALVE, don't use a real object here as a global, make it a basic type so construction
  1068. // order doesn't screw us (Alfred)
  1069. //extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
  1070. extern CRYPTOPP_DLL const char *DEFAULT_CHANNEL;
  1071. //! \brief Channel for additional authenticated data
  1072. //! \details AAD_CHANNEL is equal to "AAD"
  1073. extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
  1074. //! \brief Interface for buffered transformations
  1075. //! \details BufferedTransformation is a generalization of BlockTransformation,
  1076. //! StreamTransformation and HashTransformation.
  1077. //! \details A buffered transformation is an object that takes a stream of bytes as input (this may
  1078. //! be done in stages), does some computation on them, and then places the result into an internal
  1079. //! buffer for later retrieval. Any partial result already in the output buffer is not modified
  1080. //! by further input.
  1081. //! \details If a method takes a "blocking" parameter, and you pass false for it, then the method
  1082. //! will return before all input has been processed if the input cannot be processed without waiting
  1083. //! (for network buffers to become available, for example). In this case the method will return true
  1084. //! or a non-zero integer value. When this happens you must continue to call the method with the same
  1085. //! parameters until it returns false or zero, before calling any other method on it or attached
  1086. //! /p BufferedTransformation. The integer return value in this case is approximately
  1087. //! the number of bytes left to be processed, and can be used to implement a progress bar.
  1088. //! \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on
  1089. //! the signal to attached BufferedTransformation objects, with propagation decremented at each
  1090. //! step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation.
  1091. //! \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual
  1092. //! number of bytes retrieved, which is the lesser of the request number and MaxRetrievable().
  1093. //! \details \a Most of the input functions, like Put() and PutWord32(), return the number of
  1094. //! bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value
  1095. //! means bytes remain to be processed.
  1096. //! \nosubgrouping
  1097. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
  1098. {
  1099. public:
  1100. // placed up here for CW8
  1101. static const std::string &NULL_CHANNEL; // same as DEFAULT_CHANNEL, for backwards compatibility
  1102. BufferedTransformation() : Algorithm(false) {}
  1103. //! \brief Provides a reference to this object
  1104. //! \returns A reference to this object
  1105. //! \details Useful for passing a temporary object to a function that takes a non-const reference
  1106. BufferedTransformation& Ref() {return *this;}
  1107. //! \name INPUT
  1108. //@{
  1109. //! \brief Input a byte for processing
  1110. //! \param inByte the 8-bit byte (octet) to be processed.
  1111. //! \param blocking specifies whether the object should block when processing input.
  1112. //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
  1113. //! \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>.
  1114. size_t Put(byte inByte, bool blocking=true)
  1115. {return Put(&inByte, 1, blocking);}
  1116. //! \brief Input a byte buffer for processing
  1117. //! \param inString the byte buffer to process
  1118. //! \param length the size of the string, in bytes
  1119. //! \param blocking specifies whether the object should block when processing input
  1120. //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
  1121. //! \details Internally, Put() calls Put2().
  1122. size_t Put(const byte *inString, size_t length, bool blocking=true)
  1123. {return Put2(inString, length, 0, blocking);}
  1124. //! Input a 16-bit word for processing.
  1125. //! \param value the 16-bit value to be processed
  1126. //! \param order the ByteOrder in which the word should be processed
  1127. //! \param blocking specifies whether the object should block when processing input
  1128. //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
  1129. size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1130. //! Input a 32-bit word for processing.
  1131. //! \param value the 32-bit value to be processed.
  1132. //! \param order the ByteOrder in which the word should be processed.
  1133. //! \param blocking specifies whether the object should block when processing input.
  1134. //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
  1135. size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1136. //! \brief Request space which can be written into by the caller
  1137. //! \param size the requested size of the buffer
  1138. //! \details The purpose of this method is to help avoid extra memory allocations.
  1139. //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
  1140. //! size is the requested size of the buffer. When the call returns, size is the size of
  1141. //! the array returned to the caller.
  1142. //! \details The base class implementation sets size to 0 and returns NULL.
  1143. //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
  1144. //! an ArraySink, the pointer to the array is returned and the size is remaining size.
  1145. virtual byte * CreatePutSpace(size_t &size)
  1146. {size=0; return NULL;}
  1147. //! \brief Determines whether input can be modifed by the callee
  1148. //! \returns true if input can be modified, false otherwise
  1149. //! \details The base class implementation returns false.
  1150. virtual bool CanModifyInput() const
  1151. {return false;}
  1152. //! \brief Input multiple bytes that may be modified by callee.
  1153. //! \param inString the byte buffer to process
  1154. //! \param length the size of the string, in bytes
  1155. //! \param blocking specifies whether the object should block when processing input
  1156. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1157. //! number of bytes that were \a not processed
  1158. size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
  1159. {return PutModifiable2(inString, length, 0, blocking);}
  1160. //! \brief Signals the end of messages to the object
  1161. //! \param propagation the number of attached transformations the MessageEnd() signal should be passed
  1162. //! \param blocking specifies whether the object should block when processing input
  1163. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1164. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1165. bool MessageEnd(int propagation=-1, bool blocking=true)
  1166. {return !!Put2(NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
  1167. //! \brief Input multiple bytes for processing and signal the end of a message
  1168. //! \param inString the byte buffer to process
  1169. //! \param length the size of the string, in bytes
  1170. //! \param propagation the number of attached transformations the MessageEnd() signal should be passed
  1171. //! \param blocking specifies whether the object should block when processing input
  1172. //! \details Internally, PutMessageEnd() calls Put2() with a modified propagation to
  1173. //! ensure all attached transformations finish processing the message.
  1174. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1175. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1176. size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
  1177. {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
  1178. //! \brief Input multiple bytes for processing
  1179. //! \param inString the byte buffer to process
  1180. //! \param length the size of the string, in bytes
  1181. //! \param messageEnd means how many filters to signal MessageEnd() to, including this one
  1182. //! \param blocking specifies whether the object should block when processing input
  1183. //! \details Derived classes must implement Put2().
  1184. virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
  1185. //! \brief Input multiple bytes that may be modified by callee.
  1186. //! \param inString the byte buffer to process.
  1187. //! \param length the size of the string, in bytes.
  1188. //! \param messageEnd means how many filters to signal MessageEnd() to, including this one.
  1189. //! \param blocking specifies whether the object should block when processing input.
  1190. //! \details Internally, PutModifiable2() calls Put2().
  1191. virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
  1192. {return Put2(inString, length, messageEnd, blocking);}
  1193. //! \brief thrown by objects that have not implemented nonblocking input processing
  1194. struct BlockingInputOnly : public NotImplemented
  1195. {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
  1196. //@}
  1197. //! \name WAITING
  1198. //@{
  1199. //! \brief Retrieves the maximum number of waitable objects
  1200. unsigned int GetMaxWaitObjectCount() const;
  1201. //! \brief Retrieves waitable objects
  1202. //! \param container the wait container to receive the references to the objects
  1203. //! \param callStack CallStack object used to select waitable objects
  1204. //! \details GetWaitObjects is usually called in one of two ways. First, it can
  1205. //! be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
  1206. //! Second, if in an outer GetWaitObjects() method that itself takes a callStack
  1207. //! parameter, it can be called like
  1208. //! <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
  1209. void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
  1210. //@} // WAITING
  1211. //! \name SIGNALS
  1212. //@{
  1213. //! \brief Initialize or reinitialize this object, without signal propagation
  1214. //! \param parameters a set of NameValuePairs used to initialize this object
  1215. //! \throws NotImplemented
  1216. //! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
  1217. //! number of arbitrarily typed arguments. The function avoids the need for multiple constuctors providing
  1218. //! all possible combintations of configurable parameters.
  1219. //! \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization
  1220. //! should be propagated, then use the Initialize() function.
  1221. //! \details Setting propagation to <tt>-1</tt> means unlimited propagation.
  1222. //! \details If a derived class does not override IsolatedInitialize(), then the base class throws
  1223. //! NotImplemented.
  1224. virtual void IsolatedInitialize(const NameValuePairs &parameters) {
  1225. CRYPTOPP_UNUSED(parameters);
  1226. throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
  1227. }
  1228. //! \brief Flushes data buffered by this object, without signal propagation
  1229. //! \param hardFlush indicates whether all data should be flushed
  1230. //! \param blocking specifies whether the object should block when processing input
  1231. //! \note hardFlush must be used with care
  1232. virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
  1233. //! \brief Marks the end of a series of messages, without signal propagation
  1234. //! \param blocking specifies whether the object should block when completing the processing on
  1235. //! the current series of messages
  1236. virtual bool IsolatedMessageSeriesEnd(bool blocking)
  1237. {CRYPTOPP_UNUSED(blocking); return false;}
  1238. //! \brief Initialize or reinitialize this object, with signal propagation
  1239. //! \param parameters a set of NameValuePairs used to initialize or reinitialize this object
  1240. //! and attached transformations
  1241. //! \param propagation the number of attached transformations the Initialize() signal should be passed
  1242. //! \details Initialize() is used to initialize or reinitialize an object using a variable number of
  1243. //! arbitrarily typed arguments. The function avoids the need for multiple constuctors providing
  1244. //! all possible combintations of configurable parameters.
  1245. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1246. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1247. virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
  1248. //! \brief Flush buffered input and/or output, with signal propagation
  1249. //! \param hardFlush is used to indicate whether all data should be flushed
  1250. //! \param propagation the number of attached transformations the Flush() signal should be passed
  1251. //! \param blocking specifies whether the object should block when processing input
  1252. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1253. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1254. //! \note Hard flushes must be used with care. It means try to process and output everything, even if
  1255. //! there may not be enough data to complete the action. For example, hard flushing a HexDecoder
  1256. //! would cause an error if you do it after inputing an odd number of hex encoded characters.
  1257. //! \note For some types of filters, like ZlibDecompressor, hard flushes can only
  1258. //! be done at "synchronization points". These synchronization points are positions in the data
  1259. //! stream that are created by hard flushes on the corresponding reverse filters, in this
  1260. //! example ZlibCompressor. This is useful when zlib compressed data is moved across a
  1261. //! network in packets and compression state is preserved across packets, as in the SSH2 protocol.
  1262. virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
  1263. //! \brief Marks the end of a series of messages, with signal propagation
  1264. //! \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
  1265. //! \param blocking specifies whether the object should block when processing input
  1266. //! \details Each object that receives the signal will perform its processing, decrement
  1267. //! propagation, and then pass the signal on to attached transformations if the value is not 0.
  1268. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1269. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1270. //! \note There should be a MessageEnd() immediately before MessageSeriesEnd().
  1271. virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
  1272. //! \brief Set propagation of automatically generated and transferred signals
  1273. //! \param propagation then new value
  1274. //! \details Setting propagation to <tt>0</tt> means do not automaticly generate signals. Setting
  1275. //! propagation to <tt>-1</tt> means unlimited propagation.
  1276. virtual void SetAutoSignalPropagation(int propagation)
  1277. {CRYPTOPP_UNUSED(propagation);}
  1278. //! \brief Retrieve automatic signal propagation value
  1279. virtual int GetAutoSignalPropagation() const {return 0;}
  1280. public:
  1281. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1282. void Close() {MessageEnd();}
  1283. #endif
  1284. //@}
  1285. //! \name RETRIEVAL OF ONE MESSAGE
  1286. //@{
  1287. //! \brief Provides the number of bytes ready for retrieval
  1288. //! \returns the number of bytes ready for retrieval
  1289. //! \details All retrieval functions return the actual number of bytes retrieved, which is
  1290. //! the lesser of the request number and MaxRetrievable()
  1291. virtual lword MaxRetrievable() const;
  1292. //! \brief Determines whether bytes are ready for retrieval
  1293. //! \returns true if bytes are available for retrieval, false otherwise
  1294. virtual bool AnyRetrievable() const;
  1295. //! \brief Retrieve a 8-bit byte
  1296. //! \param outByte the 8-bit value to be retrieved
  1297. //! \returns the number of bytes consumed during the call.
  1298. //! \details Use the return value of Get to detect short reads.
  1299. virtual size_t Get(byte &outByte);
  1300. //! \brief Retrieve a block of bytes
  1301. //! \param outString a block of bytes
  1302. //! \param getMax the number of bytes to Get
  1303. //! \returns the number of bytes consumed during the call.
  1304. //! \details Use the return value of Get to detect short reads.
  1305. virtual size_t Get(byte *outString, size_t getMax);
  1306. //! \brief Peek a 8-bit byte
  1307. //! \param outByte the 8-bit value to be retrieved
  1308. //! \returns the number of bytes read during the call.
  1309. //! \details Peek does not remove bytes from the object. Use the return value of
  1310. //! Get to detect short reads.
  1311. virtual size_t Peek(byte &outByte) const;
  1312. //! \brief Peek a block of bytes
  1313. //! \param outString a block of bytes
  1314. //! \param peekMax the number of bytes to Peek
  1315. //! \returns the number of bytes read during the call.
  1316. //! \details Peek does not remove bytes from the object. Use the return value of
  1317. //! Get to detect short reads.
  1318. virtual size_t Peek(byte *outString, size_t peekMax) const;
  1319. //! \brief Retrieve a 16-bit word
  1320. //! \param value the 16-bit value to be retrieved
  1321. //! \param order the ByteOrder in which the word should be retrieved
  1322. //! \returns the number of bytes consumed during the call.
  1323. //! \details Use the return value of GetWord16 to detect short reads.
  1324. size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
  1325. //! \brief Retrieve a 32-bit word
  1326. //! \param value the 32-bit value to be retrieved
  1327. //! \param order the ByteOrder in which the word should be retrieved
  1328. //! \returns the number of bytes consumed during the call.
  1329. //! \details Use the return value of GetWord16 to detect short reads.
  1330. size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
  1331. //! \brief Peek a 16-bit word
  1332. //! \param value the 16-bit value to be retrieved
  1333. //! \param order the ByteOrder in which the word should be retrieved
  1334. //! \returns the number of bytes consumed during the call.
  1335. //! \details Peek does not consume bytes in the stream. Use the return value
  1336. //! of GetWord16 to detect short reads.
  1337. size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
  1338. //! \brief Peek a 32-bit word
  1339. //! \param value the 32-bit value to be retrieved
  1340. //! \param order the ByteOrder in which the word should be retrieved
  1341. //! \returns the number of bytes consumed during the call.
  1342. //! \details Peek does not consume bytes in the stream. Use the return value
  1343. //! of GetWord16 to detect short reads.
  1344. size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
  1345. //! move transferMax bytes of the buffered output to target as input
  1346. //! \brief Transfer bytes from this object to another BufferedTransformation
  1347. //! \param target the destination BufferedTransformation
  1348. //! \param transferMax the number of bytes to transfer
  1349. //! \param channel the channel on which the transfer should occur
  1350. //! \returns the number of bytes transferred during the call.
  1351. //! \details TransferTo removes bytes from this object and moves them to the destination.
  1352. //! \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2.
  1353. lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
  1354. {TransferTo2(target, transferMax, channel); return transferMax;}
  1355. //! \brief Discard skipMax bytes from the output buffer
  1356. //! \param skipMax the number of bytes to discard
  1357. //! \details Skip always returns skipMax.
  1358. virtual lword Skip(lword skipMax=LWORD_MAX);
  1359. //! copy copyMax bytes of the buffered output to target as input
  1360. //! \brief Copy bytes from this object to another BufferedTransformation
  1361. //! \param target the destination BufferedTransformation
  1362. //! \param copyMax the number of bytes to copy
  1363. //! \param channel the channel on which the transfer should occur
  1364. //! \returns the number of bytes copied during the call.
  1365. //! \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
  1366. //! \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2.
  1367. lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
  1368. {return CopyRangeTo(target, 0, copyMax, channel);}
  1369. //! \brief Copy bytes from this object using an index to another BufferedTransformation
  1370. //! \param target the destination BufferedTransformation
  1371. //! \param position the 0-based index of the byte stream to begin the copying
  1372. //! \param copyMax the number of bytes to copy
  1373. //! \param channel the channel on which the transfer should occur
  1374. //! \returns the number of bytes copied during the call.
  1375. //! \details CopyTo copies bytes from this object to the destination. The bytes remain in this
  1376. //! object. Copying begins at the index position in the current stream, and not from an absolute
  1377. //! position in the stream.
  1378. //! \details The function returns the new position in the stream after transferring the bytes starting at the index.
  1379. lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
  1380. {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
  1381. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1382. unsigned long MaxRetrieveable() const {return MaxRetrievable();}
  1383. #endif
  1384. //@}
  1385. //! \name RETRIEVAL OF MULTIPLE MESSAGES
  1386. //@{
  1387. //! \brief Provides the number of bytes ready for retrieval
  1388. //! \returns the number of bytes ready for retrieval
  1389. virtual lword TotalBytesRetrievable() const;
  1390. //! \brief Provides the number of meesages processed by this object
  1391. //! \returns the number of meesages processed by this object
  1392. //! \details NumberOfMessages returns number of times MessageEnd() has been
  1393. //! received minus messages retrieved or skipped
  1394. virtual unsigned int NumberOfMessages() const;
  1395. //! \brief Determines if any messages are available for retrieval
  1396. //! \returns true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
  1397. //! \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
  1398. virtual bool AnyMessages() const;
  1399. //! \brief Start retrieving the next message
  1400. //! \returns true if a message is ready for retrieval
  1401. //! \details GetNextMessage() returns true if a message is ready for retrieval; false
  1402. //! if no more messages exist or this message is not completely retrieved.
  1403. virtual bool GetNextMessage();
  1404. //! \brief Skip a number of meessages
  1405. //! \returns 0 if the requested number of messages was skipped, non-0 otherwise
  1406. //! \details SkipMessages() skips count number of messages. If there is an AttachedTransformation()
  1407. //! then SkipMessages() is called on the attached transformation. If there is no attached
  1408. //! transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo().
  1409. virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
  1410. //! \brief Transfer messages from this object to another BufferedTransformation
  1411. //! \param target the destination BufferedTransformation
  1412. //! \param count the number of messages to transfer
  1413. //! \param channel the channel on which the transfer should occur
  1414. //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1415. //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination.
  1416. //! If all bytes are not transferred for a message, then processing stops and the number of remaining
  1417. //! bytes is returned. TransferMessagesTo() does not proceed to the next message.
  1418. //! \details A return value of 0 indicates all messages were successfully transferred.
  1419. unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
  1420. {TransferMessagesTo2(target, count, channel); return count;}
  1421. //! \brief Copies messages from this object to another BufferedTransformation
  1422. //! \param target the destination BufferedTransformation
  1423. //! \param count the number of messages to transfer
  1424. //! \param channel the channel on which the transfer should occur
  1425. //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1426. //! \details CopyMessagesTo copies messages from this object and copies them to the destination.
  1427. //! If all bytes are not transferred for a message, then processing stops and the number of remaining
  1428. //! bytes is returned. CopyMessagesTo() does not proceed to the next message.
  1429. //! \details A return value of 0 indicates all messages were successfully copied.
  1430. unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
  1431. //!
  1432. virtual void SkipAll();
  1433. //!
  1434. void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
  1435. {TransferAllTo2(target, channel);}
  1436. //!
  1437. void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
  1438. virtual bool GetNextMessageSeries() {return false;}
  1439. virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
  1440. virtual unsigned int NumberOfMessageSeries() const {return 0;}
  1441. //@}
  1442. //! \name NON-BLOCKING TRANSFER OF OUTPUT
  1443. //@{
  1444. // upon return, byteCount contains number of bytes that have finished being transfered,
  1445. // and returns the number of bytes left in the current transfer block
  1446. //! \brief Transfer bytes from this object to another BufferedTransformation
  1447. //! \param target the destination BufferedTransformation
  1448. //! \param byteCount the number of bytes to transfer
  1449. //! \param channel the channel on which the transfer should occur
  1450. //! \param blocking specifies whether the object should block when processing input
  1451. //! \returns the number of bytes that remain in the transfer block (i.e., bytes not transferred)
  1452. //! \details TransferTo removes bytes from this object and moves them to the destination.
  1453. //! Transfer begins at the index position in the current stream, and not from an absolute
  1454. //! position in the stream.
  1455. //! \details byteCount is an \a IN and \a OUT parameter. When the call is made,
  1456. //! byteCount is the requested size of the transfer. When the call returns, byteCount is
  1457. //! the number of bytes that were transferred.
  1458. virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
  1459. // upon return, begin contains the start position of data yet to be finished copying,
  1460. // and returns the number of bytes left in the current transfer block
  1461. //! \brief Copy bytes from this object to another BufferedTransformation
  1462. //! \param target the destination BufferedTransformation
  1463. //! \param begin the 0-based index of the first byte to copy in the stream
  1464. //! \param end the 0-based index of the last byte to copy in the stream
  1465. //! \param channel the channel on which the transfer should occur
  1466. //! \param blocking specifies whether the object should block when processing input
  1467. //! \returns the number of bytes that remain in the copy block (i.e., bytes not copied)
  1468. //! \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not
  1469. //! removed from this object. Copying begins at the index position in the current stream, and
  1470. //! not from an absolute position in the stream.
  1471. //! \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the
  1472. //! starting position of the copy. When the call returns, begin is the position of the first
  1473. //! byte that was \a not copied (which may be different tahn end). begin can be used for
  1474. //! subsequent calls to CopyRangeTo2.
  1475. virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
  1476. // upon return, messageCount contains number of messages that have finished being transfered,
  1477. // and returns the number of bytes left in the current transfer block
  1478. //! \brief Transfer messages from this object to another BufferedTransformation
  1479. //! \param target the destination BufferedTransformation
  1480. //! \param messageCount the number of messages to transfer
  1481. //! \param channel the channel on which the transfer should occur
  1482. //! \param blocking specifies whether the object should block when processing input
  1483. //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1484. //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination.
  1485. size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
  1486. // returns the number of bytes left in the current transfer block
  1487. //! \brief Transfer all bytes from this object to another BufferedTransformation
  1488. //! \param target the destination BufferedTransformation
  1489. //! \param channel the channel on which the transfer should occur
  1490. //! \param blocking specifies whether the object should block when processing input
  1491. //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1492. //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination.
  1493. size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
  1494. //@}
  1495. //! \name CHANNELS
  1496. //@{
  1497. //! \brief Exception thrown when a filter does not support named channels
  1498. struct NoChannelSupport : public NotImplemented
  1499. {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
  1500. //! \brief Exception thrown when a filter does not recognize a named channel
  1501. struct InvalidChannelName : public InvalidArgument
  1502. {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
  1503. //! \brief Input a byte for processing on a channel
  1504. //! \param channel the channel to process the data.
  1505. //! \param inByte the 8-bit byte (octet) to be processed.
  1506. //! \param blocking specifies whether the object should block when processing input.
  1507. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1508. //! number of bytes that were \a not processed.
  1509. size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
  1510. {return ChannelPut(channel, &inByte, 1, blocking);}
  1511. //! \brief Input a byte buffer for processing on a channel
  1512. //! \param channel the channel to process the data
  1513. //! \param inString the byte buffer to process
  1514. //! \param length the size of the string, in bytes
  1515. //! \param blocking specifies whether the object should block when processing input
  1516. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1517. //! number of bytes that were \a not processed.
  1518. size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
  1519. {return ChannelPut2(channel, inString, length, 0, blocking);}
  1520. //! \brief Input multiple bytes that may be modified by callee on a channel
  1521. //! \param channel the channel to process the data.
  1522. //! \param inString the byte buffer to process
  1523. //! \param length the size of the string, in bytes
  1524. //! \param blocking specifies whether the object should block when processing input
  1525. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1526. //! number of bytes that were \a not processed.
  1527. size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
  1528. {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
  1529. //! \brief Input a 16-bit word for processing on a channel.
  1530. //! \param channel the channel to process the data.
  1531. //! \param value the 16-bit value to be processed.
  1532. //! \param order the ByteOrder in which the word should be processed.
  1533. //! \param blocking specifies whether the object should block when processing input.
  1534. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1535. //! number of bytes that were \a not processed.
  1536. size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1537. //! \brief Input a 32-bit word for processing on a channel.
  1538. //! \param channel the channel to process the data.
  1539. //! \param value the 32-bit value to be processed.
  1540. //! \param order the ByteOrder in which the word should be processed.
  1541. //! \param blocking specifies whether the object should block when processing input.
  1542. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1543. //! number of bytes that were \a not processed.
  1544. size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1545. //! \brief Signal the end of a message
  1546. //! \param channel the channel to process the data.
  1547. //! \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed
  1548. //! \param blocking specifies whether the object should block when processing input
  1549. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1550. //! number of bytes that were \a not processed.
  1551. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1552. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1553. bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
  1554. {return !!ChannelPut2(channel, NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
  1555. //! \brief Input multiple bytes for processing and signal the end of a message
  1556. //! \param channel the channel to process the data.
  1557. //! \param inString the byte buffer to process
  1558. //! \param length the size of the string, in bytes
  1559. //! \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed
  1560. //! \param blocking specifies whether the object should block when processing input
  1561. //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
  1562. //! number of bytes that were \a not processed.
  1563. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1564. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1565. size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
  1566. {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
  1567. //! \brief Request space which can be written into by the caller
  1568. //! \param channel the channel to process the data
  1569. //! \param size the requested size of the buffer
  1570. //! \details The purpose of this method is to help avoid extra memory allocations.
  1571. //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
  1572. //! size is the requested size of the buffer. When the call returns, size is the size of
  1573. //! the array returned to the caller.
  1574. //! \details The base class implementation sets size to 0 and returns NULL.
  1575. //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
  1576. //! an ArraySink, the pointer to the array is returned and the size is remaining size.
  1577. virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
  1578. //! \brief Input multiple bytes for processing on a channel.
  1579. //! \param channel the channel to process the data.
  1580. //! \param inString the byte buffer to process.
  1581. //! \param length the size of the string, in bytes.
  1582. //! \param messageEnd means how many filters to signal MessageEnd() to, including this one.
  1583. //! \param blocking specifies whether the object should block when processing input.
  1584. virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
  1585. //! \brief Input multiple bytes that may be modified by callee on a channel
  1586. //! \param channel the channel to process the data
  1587. //! \param inString the byte buffer to process
  1588. //! \param length the size of the string, in bytes
  1589. //! \param messageEnd means how many filters to signal MessageEnd() to, including this one
  1590. //! \param blocking specifies whether the object should block when processing input
  1591. virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
  1592. //! \brief Flush buffered input and/or output on a channel
  1593. //! \param channel the channel to flush the data
  1594. //! \param hardFlush is used to indicate whether all data should be flushed
  1595. //! \param propagation the number of attached transformations the ChannelFlush() signal should be passed
  1596. //! \param blocking specifies whether the object should block when processing input
  1597. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1598. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1599. virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
  1600. //! \brief Marks the end of a series of messages on a channel
  1601. //! \param channel the channel to signal the end of a series of messages
  1602. //! \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed
  1603. //! \param blocking specifies whether the object should block when processing input
  1604. //! \details Each object that receives the signal will perform its processing, decrement
  1605. //! propagation, and then pass the signal on to attached transformations if the value is not 0.
  1606. //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1607. //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1608. //! \note There should be a MessageEnd() immediately before MessageSeriesEnd().
  1609. virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
  1610. //! \brief Sets the default retrieval channel
  1611. //! \param channel the channel to signal the end of a series of messages
  1612. //! \note this function may not be implemented in all objects that should support it.
  1613. virtual void SetRetrievalChannel(const std::string &channel);
  1614. //@}
  1615. //! \name ATTACHMENT
  1616. /*! Some BufferedTransformation objects (e.g. Filter objects)
  1617. allow other BufferedTransformation objects to be attached. When
  1618. this is done, the first object instead of buffering its output,
  1619. sends that output to the attached object as input. The entire
  1620. attachment chain is deleted when the anchor object is destructed.
  1621. */
  1622. //@{
  1623. //! \brief Determines whether the object allows attachment
  1624. //! \returns true if the object allows an attachment, false otherwise
  1625. //! \details Sources and Filters will return true, while Sinks and other objects will return false.
  1626. virtual bool Attachable() {return false;}
  1627. //! \brief Returns the object immediately attached to this object
  1628. //! \details AttachedTransformation returns NULL if there is no attachment
  1629. virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;}
  1630. //! \brief Returns the object immediately attached to this object
  1631. //! \details AttachedTransformation returns NULL if there is no attachment
  1632. virtual const BufferedTransformation *AttachedTransformation() const
  1633. {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
  1634. //! \brief Delete the current attachment chain and attach a new one
  1635. //! \param newAttachment the new BufferedTransformation to attach
  1636. //! \throws NotImplemented
  1637. //! \details Detach delete the current attachment chain and replace it with an optional newAttachment
  1638. //! \details If a derived class does not override Detach, then the base class throws
  1639. //! NotImplemented.
  1640. virtual void Detach(BufferedTransformation *newAttachment = 0) {
  1641. CRYPTOPP_UNUSED(newAttachment); assert(!Attachable());
  1642. throw NotImplemented("BufferedTransformation: this object is not attachable");
  1643. }
  1644. //! \brief Add newAttachment to the end of attachment chain
  1645. //! \param newAttachment the attachment to add to the end of the chain
  1646. virtual void Attach(BufferedTransformation *newAttachment);
  1647. //@}
  1648. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1649. virtual ~BufferedTransformation() {}
  1650. #endif
  1651. protected:
  1652. //! \brief Decrements the propagation count while clamping at 0
  1653. //! \returns the decremented propagation or 0
  1654. static int DecrementPropagation(int propagation)
  1655. {return propagation != 0 ? propagation - 1 : 0;}
  1656. private:
  1657. byte m_buf[4]; // for ChannelPutWord16 and ChannelPutWord32, to ensure buffer isn't deallocated before non-blocking operation completes
  1658. };
  1659. //! \brief An input discarding BufferedTransformation
  1660. //! \returns a reference to a BufferedTransformation object that discards all input
  1661. CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
  1662. //! \class CryptoMaterial
  1663. //! \brief Interface for crypto material, such as public and private keys, and crypto parameters
  1664. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
  1665. {
  1666. public:
  1667. //! exception thrown when invalid crypto material is detected
  1668. class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
  1669. {
  1670. public:
  1671. explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
  1672. };
  1673. //! \brief Assign values to this object
  1674. /*! \details This function can be used to create a public key from a private key. */
  1675. virtual void AssignFrom(const NameValuePairs &source) =0;
  1676. //! \brief Check this object for errors
  1677. //! \param rng a RandomNumberGenerator for objects which use randomized testing
  1678. //! \param level the level of thoroughness
  1679. //! \returns true if the tests succeed, false otherwise
  1680. //! \details There are four levels of thoroughness:
  1681. //! <ul>
  1682. //! <li>0 - using this object won't cause a crash or exception
  1683. //! <li>1 - this object will probably function, and encrypt, sign, other operations correctly
  1684. //! <li>2 - ensure this object will function correctly, and perform reasonable security checks
  1685. //! <li>3 - perform reasonable security checks, and do checks that may take a long time
  1686. //! </ul>
  1687. //! \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
  1688. //! \details Level 1 may not check for weak keys and such.
  1689. //! \details Levels 2 and 3 are recommended.
  1690. virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
  1691. //! \brief Check this object for errors
  1692. //! \param rng a RandomNumberGenerator for objects which use randomized testing
  1693. //! \param level the level of thoroughness
  1694. //! \throws InvalidMaterial
  1695. //! \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial if validation fails.
  1696. virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
  1697. {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
  1698. //! \brief Saves a key to a BufferedTransformation
  1699. //! \param bt the destination BufferedTransformation
  1700. //! \throws NotImplemented
  1701. //! \details Save writes the material to a BufferedTransformation.
  1702. //! \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
  1703. //! includes an object identifier with an algorthm id, like a subjectPublicKeyInfo.
  1704. //! \details A "raw" key without the "key info" can be saved using a key's DEREncode method.
  1705. //! \details If a derived class does not override Save, then the base class throws
  1706. //! NotImplemented.
  1707. virtual void Save(BufferedTransformation &bt) const
  1708. {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
  1709. //! \brief Loads a key from a BufferedTransformation
  1710. //! \param bt the source BufferedTransformation
  1711. //! \throws KeyingErr
  1712. //! \details Load attempts to read material from a BufferedTransformation. If the
  1713. //! material is a key that was generated outside the library, then the following
  1714. //! usually applies:
  1715. //! <ul>
  1716. //! <li>the key should be ASN.1 BER encoded
  1717. //! <li>the key should be a "key info"
  1718. //! </ul>
  1719. //! \details "key info" means the key should have an object identifier with an algorthm id,
  1720. //! like a subjectPublicKeyInfo.
  1721. //! \details To read a "raw" key without the "key info", then call the key's BERDecode method.
  1722. //! \note Load generally does not check that the key is valid. Call Validate(), if needed.
  1723. virtual void Load(BufferedTransformation &bt)
  1724. {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
  1725. //! \brief Determines whether the object supports precomputation
  1726. //! \returns true if the object supports precomputation, false otherwise
  1727. virtual bool SupportsPrecomputation() const {return false;}
  1728. //! \brief Perform precomputation
  1729. //! \param precomputationStorage the suggested number of objects for the precompute table
  1730. //! \throws NotImplemented
  1731. //! \details The exact semantics of Precompute() varies, but it typically means calculate
  1732. //! a table of n objects that can be used later to speed up computation.
  1733. //! \details If a derived class does not override Precompute, then the base class throws
  1734. //! NotImplemented.
  1735. virtual void Precompute(unsigned int precomputationStorage) {
  1736. CRYPTOPP_UNUSED(precomputationStorage); assert(!SupportsPrecomputation());
  1737. throw NotImplemented("CryptoMaterial: this object does not support precomputation");
  1738. }
  1739. //! retrieve previously saved precomputation
  1740. virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
  1741. {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
  1742. //! save precomputation for later use
  1743. virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
  1744. {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
  1745. // for internal library use
  1746. void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
  1747. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1748. virtual ~CryptoMaterial() {}
  1749. #endif
  1750. #if (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
  1751. // Sun Studio 11/CC 5.8 workaround: it generates incorrect code when casting to an empty virtual base class
  1752. char m_sunCCworkaround;
  1753. #endif
  1754. };
  1755. //! \class GeneratableCryptoMaterial
  1756. //! \brief Interface for generatable crypto material, such as private keys and crypto parameters
  1757. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
  1758. {
  1759. public:
  1760. //! \brief Generate a random key or crypto parameters
  1761. //! \param rng a RandomNumberGenerator to produce keying material
  1762. //! \param params additional initialization parameters
  1763. //! \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
  1764. //! \details If a derived class does not override GenerateRandom, then the base class throws
  1765. //! NotImplemented.
  1766. virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs) {
  1767. CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
  1768. throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
  1769. }
  1770. //! \brief Generate a random key or crypto parameters
  1771. //! \param rng a RandomNumberGenerator to produce keying material
  1772. //! \param keySize the size of the key, in bits
  1773. //! \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
  1774. //! \details GenerateRandomWithKeySize calls GenerateRandom with a NameValuePairs
  1775. //! object with only "KeySize"
  1776. void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
  1777. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1778. virtual ~GeneratableCryptoMaterial() {}
  1779. #endif
  1780. };
  1781. //! \brief Interface for public keys
  1782. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
  1783. {
  1784. };
  1785. //! \brief Interface for private keys
  1786. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
  1787. {
  1788. };
  1789. //! \brief Interface for crypto prameters
  1790. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
  1791. {
  1792. };
  1793. //! \brief Interface for asymmetric algorithms
  1794. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
  1795. {
  1796. public:
  1797. //! returns a reference to the crypto material used by this object
  1798. virtual CryptoMaterial & AccessMaterial() =0;
  1799. //! returns a const reference to the crypto material used by this object
  1800. virtual const CryptoMaterial & GetMaterial() const =0;
  1801. //! for backwards compatibility, calls AccessMaterial().Load(bt)
  1802. void BERDecode(BufferedTransformation &bt)
  1803. {AccessMaterial().Load(bt);}
  1804. //! for backwards compatibility, calls GetMaterial().Save(bt)
  1805. void DEREncode(BufferedTransformation &bt) const
  1806. {GetMaterial().Save(bt);}
  1807. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1808. virtual ~AsymmetricAlgorithm() {}
  1809. #endif
  1810. };
  1811. //! \brief Interface for asymmetric algorithms using public keys
  1812. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
  1813. {
  1814. public:
  1815. // VC60 workaround: no co-variant return type
  1816. CryptoMaterial & AccessMaterial() {return AccessPublicKey();}
  1817. const CryptoMaterial & GetMaterial() const {return GetPublicKey();}
  1818. virtual PublicKey & AccessPublicKey() =0;
  1819. virtual const PublicKey & GetPublicKey() const {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
  1820. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1821. virtual ~PublicKeyAlgorithm() {}
  1822. #endif
  1823. };
  1824. //! \brief Interface for asymmetric algorithms using private keys
  1825. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
  1826. {
  1827. public:
  1828. CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
  1829. const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
  1830. virtual PrivateKey & AccessPrivateKey() =0;
  1831. virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
  1832. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1833. virtual ~PrivateKeyAlgorithm() {}
  1834. #endif
  1835. };
  1836. //! \brief Interface for key agreement algorithms
  1837. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
  1838. {
  1839. public:
  1840. CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
  1841. const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
  1842. virtual CryptoParameters & AccessCryptoParameters() =0;
  1843. virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
  1844. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1845. virtual ~KeyAgreementAlgorithm() {}
  1846. #endif
  1847. };
  1848. //! \brief Interface for public-key encryptors and decryptors
  1849. /*! This class provides an interface common to encryptors and decryptors
  1850. for querying their plaintext and ciphertext lengths.
  1851. */
  1852. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
  1853. {
  1854. public:
  1855. virtual ~PK_CryptoSystem() {}
  1856. //! maximum length of plaintext for a given ciphertext length
  1857. /*! \note This function returns 0 if ciphertextLength is not valid (too long or too short). */
  1858. virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
  1859. //! calculate length of ciphertext given length of plaintext
  1860. /*! \note This function returns 0 if plaintextLength is not valid (too long). */
  1861. virtual size_t CiphertextLength(size_t plaintextLength) const =0;
  1862. //! this object supports the use of the parameter with the given name
  1863. /*! some possible parameter names: EncodingParameters, KeyDerivationParameters */
  1864. virtual bool ParameterSupported(const char *name) const =0;
  1865. //! return fixed ciphertext length, if one exists, otherwise return 0
  1866. /*! \note "Fixed" here means length of ciphertext does not depend on length of plaintext.
  1867. It usually does depend on the key length. */
  1868. virtual size_t FixedCiphertextLength() const {return 0;}
  1869. //! return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0
  1870. virtual size_t FixedMaxPlaintextLength() const {return 0;}
  1871. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1872. size_t MaxPlainTextLength(size_t cipherTextLength) const {return MaxPlaintextLength(cipherTextLength);}
  1873. size_t CipherTextLength(size_t plainTextLength) const {return CiphertextLength(plainTextLength);}
  1874. #endif
  1875. };
  1876. //! \class PK_Encryptor
  1877. //! \brief Interface for public-key encryptors
  1878. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
  1879. {
  1880. public:
  1881. //! \brief Exception thrown when trying to encrypt plaintext of invalid length
  1882. class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
  1883. {
  1884. public:
  1885. InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
  1886. };
  1887. //! \brief Encrypt a byte string
  1888. //! \param rng a RandomNumberGenerator derived class
  1889. //! \param plaintext the plaintext byte buffer
  1890. //! \param plaintextLength the size of the plaintext byte buffer
  1891. //! \param ciphertext a byte buffer to hold the encrypted string
  1892. //! \param parameters additional configuration options
  1893. //! \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
  1894. //! \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
  1895. //! byte buffer is large enough.
  1896. //! \sa PK_Decryptor
  1897. virtual void Encrypt(RandomNumberGenerator &rng,
  1898. const byte *plaintext, size_t plaintextLength,
  1899. byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
  1900. //! \brief Create a new encryption filter
  1901. //! \note The caller is responsible for deleting the returned pointer.
  1902. //! \note Encoding parameters should be passed in the "EP" channel.
  1903. virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
  1904. BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
  1905. };
  1906. //! \class PK_Decryptor
  1907. //! \brief Interface for public-key decryptors
  1908. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
  1909. {
  1910. public:
  1911. //! \brief Decrypt a byte string
  1912. //! \param rng a RandomNumberGenerator derived class
  1913. //! \param ciphertext the encrypted byte buffer
  1914. //! \param ciphertextLength the size of the encrypted byte buffer
  1915. //! \param plaintext a byte buffer to hold the decrypted string
  1916. //! \param parameters additional configuration options
  1917. //! \returns the result of the decryption operation
  1918. //! \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
  1919. //! byte buffer is large enough
  1920. //! \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
  1921. //! is valid and holds the the actual length of the plaintext recovered.
  1922. //! on success. The result is undefined if decryption failed. If DecodingResult::isValidCoding
  1923. //! is false, then DecodingResult::messageLength is undefined.
  1924. //! \sa PK_Encryptor
  1925. virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
  1926. const byte *ciphertext, size_t ciphertextLength,
  1927. byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
  1928. //! create a new decryption filter
  1929. /*! \note caller is responsible for deleting the returned pointer
  1930. */
  1931. virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
  1932. BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
  1933. //! decrypt a fixed size ciphertext
  1934. DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
  1935. {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
  1936. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  1937. virtual ~PK_Decryptor() {}
  1938. #endif
  1939. };
  1940. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1941. typedef PK_CryptoSystem PK_FixedLengthCryptoSystem;
  1942. typedef PK_Encryptor PK_FixedLengthEncryptor;
  1943. typedef PK_Decryptor PK_FixedLengthDecryptor;
  1944. #endif
  1945. //! \brief Interface for public-key signers and verifiers
  1946. /*! This class provides an interface common to signers and verifiers
  1947. for querying scheme properties.
  1948. */
  1949. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
  1950. {
  1951. public:
  1952. //! invalid key exception, may be thrown by any function in this class if the private or public key has a length that can't be used
  1953. class CRYPTOPP_DLL InvalidKeyLength : public Exception
  1954. {
  1955. public:
  1956. InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
  1957. };
  1958. //! key too short exception, may be thrown by any function in this class if the private or public key is too short to sign or verify anything
  1959. class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
  1960. {
  1961. public:
  1962. KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
  1963. };
  1964. virtual ~PK_SignatureScheme() {}
  1965. //! signature length if it only depends on the key, otherwise 0
  1966. virtual size_t SignatureLength() const =0;
  1967. //! maximum signature length produced for a given length of recoverable message part
  1968. virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
  1969. {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
  1970. //! length of longest message that can be recovered, or 0 if this signature scheme does not support message recovery
  1971. virtual size_t MaxRecoverableLength() const =0;
  1972. //! length of longest message that can be recovered from a signature of given length, or 0 if this signature scheme does not support message recovery
  1973. virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
  1974. //! requires a random number generator to sign
  1975. /*! if this returns false, NullRNG() can be passed to functions that take RandomNumberGenerator & */
  1976. virtual bool IsProbabilistic() const =0;
  1977. //! whether or not a non-recoverable message part can be signed
  1978. virtual bool AllowNonrecoverablePart() const =0;
  1979. //! if this function returns true, during verification you must input the signature before the message, otherwise you can input it at anytime */
  1980. virtual bool SignatureUpfront() const {return false;}
  1981. //! whether you must input the recoverable part before the non-recoverable part during signing
  1982. virtual bool RecoverablePartFirst() const =0;
  1983. };
  1984. //! \brief Interface for accumulating messages to be signed or verified
  1985. /*! Only Update() should be called
  1986. on this class. No other functions inherited from HashTransformation should be called.
  1987. */
  1988. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
  1989. {
  1990. public:
  1991. //! should not be called on PK_MessageAccumulator
  1992. unsigned int DigestSize() const
  1993. {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
  1994. //! should not be called on PK_MessageAccumulator
  1995. void TruncatedFinal(byte *digest, size_t digestSize)
  1996. {
  1997. CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
  1998. throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
  1999. }
  2000. };
  2001. //! \brief Interface for public-key signers
  2002. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
  2003. {
  2004. public:
  2005. //! create a new HashTransformation to accumulate the message to be signed
  2006. virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
  2007. virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
  2008. //! sign and delete messageAccumulator (even in case of exception thrown)
  2009. /*! \pre size of signature == MaxSignatureLength()
  2010. \returns actual signature length
  2011. */
  2012. virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
  2013. //! sign and restart messageAccumulator
  2014. /*! \pre size of signature == MaxSignatureLength()
  2015. \returns actual signature length
  2016. */
  2017. virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
  2018. //! sign a message
  2019. /*! \pre size of signature == MaxSignatureLength()
  2020. \returns actual signature length
  2021. */
  2022. virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
  2023. //! sign a recoverable message
  2024. /*! \pre size of signature == MaxSignatureLength(recoverableMessageLength)
  2025. \returns actual signature length
  2026. */
  2027. virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
  2028. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
  2029. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  2030. virtual ~PK_Signer() {}
  2031. #endif
  2032. };
  2033. //! \brief Interface for public-key signature verifiers
  2034. /*! The Recover* functions throw NotImplemented if the signature scheme does not support
  2035. message recovery.
  2036. The Verify* functions throw InvalidDataFormat if the scheme does support message
  2037. recovery and the signature contains a non-empty recoverable message part. The
  2038. Recovery* functions should be used in that case.
  2039. */
  2040. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
  2041. {
  2042. public:
  2043. //! create a new HashTransformation to accumulate the message to be verified
  2044. virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
  2045. //! input signature into a message accumulator
  2046. virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
  2047. //! check whether messageAccumulator contains a valid signature and message, and delete messageAccumulator (even in case of exception thrown)
  2048. virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
  2049. //! check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
  2050. virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
  2051. //! check whether input signature is a valid signature for input message
  2052. virtual bool VerifyMessage(const byte *message, size_t messageLen,
  2053. const byte *signature, size_t signatureLength) const;
  2054. //! recover a message from its signature
  2055. /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
  2056. */
  2057. virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
  2058. //! recover a message from its signature
  2059. /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
  2060. */
  2061. virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
  2062. //! recover a message from its signature
  2063. /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
  2064. */
  2065. virtual DecodingResult RecoverMessage(byte *recoveredMessage,
  2066. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
  2067. const byte *signature, size_t signatureLength) const;
  2068. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  2069. virtual ~PK_Verifier() {}
  2070. #endif
  2071. };
  2072. //! \brief Interface for domains of simple key agreement protocols
  2073. /*! A key agreement domain is a set of parameters that must be shared
  2074. by two parties in a key agreement protocol, along with the algorithms
  2075. for generating key pairs and deriving agreed values.
  2076. */
  2077. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
  2078. {
  2079. public:
  2080. //! return length of agreed value produced
  2081. virtual unsigned int AgreedValueLength() const =0;
  2082. //! return length of private keys in this domain
  2083. virtual unsigned int PrivateKeyLength() const =0;
  2084. //! return length of public keys in this domain
  2085. virtual unsigned int PublicKeyLength() const =0;
  2086. //! generate private key
  2087. /*! \pre size of privateKey == PrivateKeyLength() */
  2088. virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  2089. //! generate public key
  2090. /*! re size of publicKey == PublicKeyLength() */
  2091. virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  2092. //! generate private/public key pair
  2093. /*! \note equivalent to calling GeneratePrivateKey() and then GeneratePublicKey() */
  2094. virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  2095. //! derive agreed value from your private key and couterparty's public key, return false in case of failure
  2096. /*! \note If you have previously validated the public key, use validateOtherPublicKey=false to save time.
  2097. re size of agreedValue == AgreedValueLength()
  2098. \pre length of privateKey == PrivateKeyLength()
  2099. \pre length of otherPublicKey == PublicKeyLength()
  2100. */
  2101. virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
  2102. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  2103. virtual ~SimpleKeyAgreementDomain() {}
  2104. #endif
  2105. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  2106. bool ValidateDomainParameters(RandomNumberGenerator &rng) const
  2107. {return GetCryptoParameters().Validate(rng, 2);}
  2108. #endif
  2109. };
  2110. //! \brief Interface for domains of authenticated key agreement protocols
  2111. /*! In an authenticated key agreement protocol, each party has two
  2112. key pairs. The long-lived key pair is called the static key pair,
  2113. and the short-lived key pair is called the ephemeral key pair.
  2114. */
  2115. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
  2116. {
  2117. public:
  2118. //! return length of agreed value produced
  2119. virtual unsigned int AgreedValueLength() const =0;
  2120. //! return length of static private keys in this domain
  2121. virtual unsigned int StaticPrivateKeyLength() const =0;
  2122. //! return length of static public keys in this domain
  2123. virtual unsigned int StaticPublicKeyLength() const =0;
  2124. //! generate static private key
  2125. /*! \pre size of privateKey == PrivateStaticKeyLength() */
  2126. virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  2127. //! generate static public key
  2128. /*! re size of publicKey == PublicStaticKeyLength() */
  2129. virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  2130. //! generate private/public key pair
  2131. /*! \note equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey() */
  2132. virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  2133. //! return length of ephemeral private keys in this domain
  2134. virtual unsigned int EphemeralPrivateKeyLength() const =0;
  2135. //! return length of ephemeral public keys in this domain
  2136. virtual unsigned int EphemeralPublicKeyLength() const =0;
  2137. //! \brief Generate ephemeral private key
  2138. //! \pre size of privateKey == PrivateEphemeralKeyLength()
  2139. virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  2140. //! \brief Generate ephemeral public key
  2141. //! \pre size of publicKey == PublicEphemeralKeyLength()
  2142. virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  2143. //! \brief Generate private/public key pair
  2144. /*! \note equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() */
  2145. virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  2146. //! \brief Derive agreed value
  2147. //! \returns true upon success, false in case of failure
  2148. //! \details Agree() derives an agreed value from your private keys and couterparty's public keys
  2149. //! \details The ephemeral public key will always be validated. If you have previously validated the
  2150. //! static public key, use validateStaticOtherPublicKey=false to save time.
  2151. //! \pre size of agreedValue == AgreedValueLength()
  2152. //! \pre length of staticPrivateKey == StaticPrivateKeyLength()
  2153. //! \pre length of ephemeralPrivateKey == EphemeralPrivateKeyLength()
  2154. //! \pre length of staticOtherPublicKey == StaticPublicKeyLength()
  2155. //! \pre length of ephemeralOtherPublicKey == EphemeralPublicKeyLength()
  2156. virtual bool Agree(byte *agreedValue,
  2157. const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
  2158. const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
  2159. bool validateStaticOtherPublicKey=true) const =0;
  2160. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  2161. virtual ~AuthenticatedKeyAgreementDomain() {}
  2162. #endif
  2163. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  2164. bool ValidateDomainParameters(RandomNumberGenerator &rng) const
  2165. {return GetCryptoParameters().Validate(rng, 2);}
  2166. #endif
  2167. };
  2168. // interface for password authenticated key agreement protocols, not implemented yet
  2169. #if 0
  2170. //! \brief Interface for protocol sessions
  2171. /*! The methods should be called in the following order:
  2172. InitializeSession(rng, parameters); // or call initialize method in derived class
  2173. while (true)
  2174. {
  2175. if (OutgoingMessageAvailable())
  2176. {
  2177. length = GetOutgoingMessageLength();
  2178. GetOutgoingMessage(message);
  2179. ; // send outgoing message
  2180. }
  2181. if (LastMessageProcessed())
  2182. break;
  2183. ; // receive incoming message
  2184. ProcessIncomingMessage(message);
  2185. }
  2186. ; // call methods in derived class to obtain result of protocol session
  2187. */
  2188. class ProtocolSession
  2189. {
  2190. public:
  2191. //! exception thrown when an invalid protocol message is processed
  2192. class ProtocolError : public Exception
  2193. {
  2194. public:
  2195. ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
  2196. };
  2197. //! exception thrown when a function is called unexpectedly
  2198. /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
  2199. class UnexpectedMethodCall : public Exception
  2200. {
  2201. public:
  2202. UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
  2203. };
  2204. ProtocolSession() : m_rng(NULL), m_throwOnProtocolError(true), m_validState(false) {}
  2205. virtual ~ProtocolSession() {}
  2206. virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
  2207. bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
  2208. void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
  2209. bool HasValidState() const {return m_validState;}
  2210. virtual bool OutgoingMessageAvailable() const =0;
  2211. virtual unsigned int GetOutgoingMessageLength() const =0;
  2212. virtual void GetOutgoingMessage(byte *message) =0;
  2213. virtual bool LastMessageProcessed() const =0;
  2214. virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
  2215. protected:
  2216. void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
  2217. void CheckAndHandleInvalidState() const;
  2218. void SetValidState(bool valid) {m_validState = valid;}
  2219. RandomNumberGenerator *m_rng;
  2220. private:
  2221. bool m_throwOnProtocolError, m_validState;
  2222. };
  2223. class KeyAgreementSession : public ProtocolSession
  2224. {
  2225. public:
  2226. virtual unsigned int GetAgreedValueLength() const =0;
  2227. virtual void GetAgreedValue(byte *agreedValue) const =0;
  2228. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  2229. virtual ~KeyAgreementSession() {}
  2230. #endif
  2231. };
  2232. class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
  2233. {
  2234. public:
  2235. void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
  2236. const byte *myId, unsigned int myIdLength,
  2237. const byte *counterPartyId, unsigned int counterPartyIdLength,
  2238. const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
  2239. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  2240. virtual ~PasswordAuthenticatedKeyAgreementSession() {}
  2241. #endif
  2242. };
  2243. class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
  2244. {
  2245. public:
  2246. //! return whether the domain parameters stored in this object are valid
  2247. virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
  2248. {return GetCryptoParameters().Validate(rng, 2);}
  2249. virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
  2250. virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
  2251. enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
  2252. virtual bool IsValidRole(unsigned int role) =0;
  2253. virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
  2254. #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
  2255. virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
  2256. #endif
  2257. };
  2258. #endif
  2259. //! \brief Exception thrown when an ASN1 BER decoing error is encountered
  2260. class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
  2261. {
  2262. public:
  2263. BERDecodeErr() : InvalidArgument("BER decode error") {}
  2264. BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
  2265. };
  2266. //! \brief Interface for encoding and decoding ASN1 objects
  2267. //! \details Each class that derives from ASN1Object should provide a serialization format
  2268. //! that controls subobject layout. Most of the time the serialization format is
  2269. //! taken from a standard, like P1363 or an RFC.
  2270. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
  2271. {
  2272. public:
  2273. virtual ~ASN1Object() {}
  2274. //! \brief Decode this object from a BufferedTransformation
  2275. //! \param bt BufferedTransformation object
  2276. //! \details Uses Basic Encoding Rules (BER)
  2277. virtual void BERDecode(BufferedTransformation &bt) =0;
  2278. //! \brief Encode this object into a BufferedTransformation
  2279. //! \param bt BufferedTransformation object
  2280. //! \details Uses Distinguished Encoding Rules (DER)
  2281. virtual void DEREncode(BufferedTransformation &bt) const =0;
  2282. //! \brief Encode this object into a BufferedTransformation
  2283. //! \param bt BufferedTransformation object
  2284. //! \details Uses Basic Encoding Rules (BER).
  2285. //! \details This may be useful if DEREncode() would be too inefficient.
  2286. virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
  2287. };
  2288. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  2289. typedef PK_SignatureScheme PK_SignatureSystem;
  2290. typedef SimpleKeyAgreementDomain PK_SimpleKeyAgreementDomain;
  2291. typedef AuthenticatedKeyAgreementDomain PK_AuthenticatedKeyAgreementDomain;
  2292. #endif
  2293. NAMESPACE_END
  2294. #if CRYPTOPP_MSC_VERSION
  2295. # pragma warning(pop)
  2296. #endif
  2297. #endif