Counter Strike : Global Offensive Source Code
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.

1658 lines
73 KiB

  1. // cryptlib.h - written and placed in the public domain by Wei Dai
  2. /*! \file
  3. This file contains the declarations for the abstract base
  4. classes that provide a uniform interface to this library.
  5. */
  6. /*! \mainpage Crypto++ Library 5.6.1 API Reference
  7. <dl>
  8. <dt>Abstract Base Classes<dd>
  9. cryptlib.h
  10. <dt>Authenticated Encryption<dd>
  11. AuthenticatedSymmetricCipherDocumentation
  12. <dt>Symmetric Ciphers<dd>
  13. SymmetricCipherDocumentation
  14. <dt>Hash Functions<dd>
  15. SHA1, SHA224, SHA256, SHA384, SHA512, Tiger, Whirlpool, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, Weak1::MD2, Weak1::MD4, Weak1::MD5
  16. <dt>Non-Cryptographic Checksums<dd>
  17. CRC32, Adler32
  18. <dt>Message Authentication Codes<dd>
  19. VMAC, HMAC, CBC_MAC, CMAC, DMAC, TTMAC, GCM (GMAC)
  20. <dt>Random Number Generators<dd>
  21. NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG, #DefaultAutoSeededRNG
  22. <dt>Password-based Cryptography<dd>
  23. PasswordBasedKeyDerivationFunction
  24. <dt>Public Key Cryptosystems<dd>
  25. DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
  26. <dt>Public Key Signature Schemes<dd>
  27. DSA, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, RabinSS, RWSS, ESIGN
  28. <dt>Key Agreement<dd>
  29. #DH, DH2, #MQV, ECDH, ECMQV, XTR_DH
  30. <dt>Algebraic Structures<dd>
  31. Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
  32. ModularArithmetic, MontgomeryRepresentation, GFP2_ONB,
  33. GF2NP, GF256, GF2_32, EC2N, ECP
  34. <dt>Secret Sharing and Information Dispersal<dd>
  35. SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
  36. <dt>Compression<dd>
  37. Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
  38. <dt>Input Source Classes<dd>
  39. StringSource, #ArraySource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource
  40. <dt>Output Sink Classes<dd>
  41. StringSinkTemplate, ArraySink, FileSink, SocketSink, WindowsPipeSink, RandomNumberSink
  42. <dt>Filter Wrappers<dd>
  43. StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter
  44. <dt>Binary to Text Encoders and Decoders<dd>
  45. HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base32Encoder, Base32Decoder
  46. <dt>Wrappers for OS features<dd>
  47. Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer
  48. <dt>FIPS 140 related<dd>
  49. fips140.h
  50. </dl>
  51. In the DLL version of Crypto++, only the following implementation class are available.
  52. <dl>
  53. <dt>Block Ciphers<dd>
  54. AES, DES_EDE2, DES_EDE3, SKIPJACK
  55. <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
  56. ECB_Mode\<BC\>, CTR_Mode\<BC\>, CBC_Mode\<BC\>, CFB_FIPS_Mode\<BC\>, OFB_Mode\<BC\>, GCM\<AES\>
  57. <dt>Hash Functions<dd>
  58. SHA1, SHA224, SHA256, SHA384, SHA512
  59. <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
  60. RSASS\<PKCS1v15, H\>, RSASS\<PSS, H\>, RSASS_ISO\<H\>, RWSS\<P1363_EMSA2, H\>, DSA, ECDSA\<ECP, H\>, ECDSA\<EC2N, H\>
  61. <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
  62. HMAC\<H\>, CBC_MAC\<DES_EDE2\>, CBC_MAC\<DES_EDE3\>, GCM\<AES\>
  63. <dt>Random Number Generators<dd>
  64. #DefaultAutoSeededRNG (AutoSeededX917RNG\<AES\>)
  65. <dt>Key Agreement<dd>
  66. #DH
  67. <dt>Public Key Cryptosystems<dd>
  68. RSAES\<OAEP\<SHA1\> \>
  69. </dl>
  70. <p>This reference manual is a work in progress. Some classes are still lacking detailed descriptions.
  71. <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
  72. <p>Thanks to Ryan Phillips for providing the Doxygen configuration file
  73. and getting me started with this manual.
  74. */
  75. #ifndef CRYPTOPP_CRYPTLIB_H
  76. #define CRYPTOPP_CRYPTLIB_H
  77. #include "config.h"
  78. #include "stdcpp.h"
  79. NAMESPACE_BEGIN(CryptoPP)
  80. // forward declarations
  81. class Integer;
  82. class RandomNumberGenerator;
  83. class BufferedTransformation;
  84. //! used to specify a direction for a cipher to operate in (encrypt or decrypt)
  85. enum CipherDir {ENCRYPTION, DECRYPTION};
  86. //! used to represent infinite time
  87. const unsigned long INFINITE_TIME = ULONG_MAX;
  88. // VC60 workaround: using enums as template parameters causes problems
  89. template <typename ENUM_TYPE, int VALUE>
  90. struct EnumToType
  91. {
  92. static ENUM_TYPE ToEnum() {return (ENUM_TYPE)VALUE;}
  93. };
  94. enum ByteOrder {LITTLE_ENDIAN_ORDER = 0, BIG_ENDIAN_ORDER = 1};
  95. typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian;
  96. typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian;
  97. //! base class for all exceptions thrown by Crypto++
  98. class CRYPTOPP_DLL Exception : public std::exception
  99. {
  100. public:
  101. //! error types
  102. enum ErrorType {
  103. //! a method is not implemented
  104. NOT_IMPLEMENTED,
  105. //! invalid function argument
  106. INVALID_ARGUMENT,
  107. //! BufferedTransformation received a Flush(true) signal but can't flush buffers
  108. CANNOT_FLUSH,
  109. //! data integerity check (such as CRC or MAC) failed
  110. DATA_INTEGRITY_CHECK_FAILED,
  111. //! received input data that doesn't conform to expected format
  112. INVALID_DATA_FORMAT,
  113. //! error reading from input device or writing to output device
  114. IO_ERROR,
  115. //! some error not belong to any of the above categories
  116. OTHER_ERROR
  117. };
  118. explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
  119. virtual ~Exception() throw() {}
  120. const char *what() const throw() {return (m_what.c_str());}
  121. const std::string &GetWhat() const {return m_what;}
  122. void SetWhat(const std::string &s) {m_what = s;}
  123. ErrorType GetErrorType() const {return m_errorType;}
  124. void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
  125. private:
  126. ErrorType m_errorType;
  127. std::string m_what;
  128. };
  129. //! exception thrown when an invalid argument is detected
  130. class CRYPTOPP_DLL InvalidArgument : public Exception
  131. {
  132. public:
  133. explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
  134. };
  135. //! exception thrown when input data is received that doesn't conform to expected format
  136. class CRYPTOPP_DLL InvalidDataFormat : public Exception
  137. {
  138. public:
  139. explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
  140. };
  141. //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext
  142. class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
  143. {
  144. public:
  145. explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
  146. };
  147. //! exception thrown by a class if a non-implemented method is called
  148. class CRYPTOPP_DLL NotImplemented : public Exception
  149. {
  150. public:
  151. explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
  152. };
  153. //! exception thrown by a class when Flush(true) is called but it can't completely flush its buffers
  154. class CRYPTOPP_DLL CannotFlush : public Exception
  155. {
  156. public:
  157. explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
  158. };
  159. //! error reported by the operating system
  160. class CRYPTOPP_DLL OS_Error : public Exception
  161. {
  162. public:
  163. OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
  164. : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
  165. ~OS_Error() throw() {}
  166. // the operating system API that reported the error
  167. const std::string & GetOperation() const {return m_operation;}
  168. // the error code return by the operating system
  169. int GetErrorCode() const {return m_errorCode;}
  170. protected:
  171. std::string m_operation;
  172. int m_errorCode;
  173. };
  174. //! used to return decoding results
  175. struct CRYPTOPP_DLL DecodingResult
  176. {
  177. explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
  178. explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
  179. bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
  180. bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
  181. bool isValidCoding;
  182. size_t messageLength;
  183. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  184. operator size_t() const {return isValidCoding ? messageLength : 0;}
  185. #endif
  186. };
  187. //! interface for retrieving values given their names
  188. /*! \note This class is used to safely pass a variable number of arbitrarily typed arguments to functions
  189. and to read values from keys and crypto parameters.
  190. \note To obtain an object that implements NameValuePairs for the purpose of parameter
  191. passing, use the MakeParameters() function.
  192. \note To get a value from NameValuePairs, you need to know the name and the type of the value.
  193. Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports.
  194. Then look at the Name namespace documentation to see what the type of each value is, or
  195. alternatively, call GetIntValue() with the value name, and if the type is not int, a
  196. ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object.
  197. */
  198. class CRYPTOPP_NO_VTABLE NameValuePairs
  199. {
  200. public:
  201. virtual ~NameValuePairs() {}
  202. //! exception thrown when trying to retrieve a value using a different type than expected
  203. class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
  204. {
  205. public:
  206. ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
  207. : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
  208. , m_stored(stored), m_retrieving(retrieving) {}
  209. const std::type_info & GetStoredTypeInfo() const {return m_stored;}
  210. const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
  211. private:
  212. const std::type_info &m_stored;
  213. const std::type_info &m_retrieving;
  214. };
  215. //! get a copy of this object or a subobject of it
  216. template <class T>
  217. bool GetThisObject(T &object) const
  218. {
  219. return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
  220. }
  221. //! get a pointer to this object, as a pointer to T
  222. template <class T>
  223. bool GetThisPointer(T *&p) const
  224. {
  225. return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), p);
  226. }
  227. //! get a named value, returns true if the name exists
  228. template <class T>
  229. bool GetValue(const char *name, T &value) const
  230. {
  231. return GetVoidValue(name, typeid(T), &value);
  232. }
  233. //! get a named value, returns the default if the name doesn't exist
  234. template <class T>
  235. T GetValueWithDefault(const char *name, T defaultValue) const
  236. {
  237. GetValue(name, defaultValue);
  238. return defaultValue;
  239. }
  240. //! get a list of value names that can be retrieved
  241. CRYPTOPP_DLL std::string GetValueNames() const
  242. {std::string result; GetValue("ValueNames", result); return result;}
  243. //! get a named value with type int
  244. /*! used to ensure we don't accidentally try to get an unsigned int
  245. or some other type when we mean int (which is the most common case) */
  246. CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
  247. {return GetValue(name, value);}
  248. //! get a named value with type int, with default
  249. CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
  250. {return GetValueWithDefault(name, defaultValue);}
  251. //! used by derived classes to check for type mismatch
  252. CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
  253. {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
  254. template <class T>
  255. void GetRequiredParameter(const char *className, const char *name, T &value) const
  256. {
  257. if (!GetValue(name, value))
  258. throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
  259. }
  260. CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
  261. {
  262. if (!GetIntValue(name, value))
  263. throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
  264. }
  265. //! to be implemented by derived classes, users should use one of the above functions instead
  266. CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
  267. };
  268. //! namespace containing value name definitions
  269. /*! value names, types and semantics:
  270. ThisObject:ClassName (ClassName, copy of this object or a subobject)
  271. ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
  272. */
  273. DOCUMENTED_NAMESPACE_BEGIN(Name)
  274. // more names defined in argnames.h
  275. DOCUMENTED_NAMESPACE_END
  276. //! empty set of name-value pairs
  277. extern CRYPTOPP_DLL const NameValuePairs &g_nullNameValuePairs;
  278. // ********************************************************
  279. //! interface for cloning objects, this is not implemented by most classes yet
  280. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
  281. {
  282. public:
  283. virtual ~Clonable() {}
  284. //! this is not implemented by most classes yet
  285. virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
  286. };
  287. //! interface for all crypto algorithms
  288. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
  289. {
  290. public:
  291. /*! When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
  292. this constructor throws SelfTestFailure if the self test hasn't been run or fails. */
  293. Algorithm(bool checkSelfTestStatus = true);
  294. //! returns name of this algorithm, not universally implemented yet
  295. virtual std::string AlgorithmName() const {return "unknown";}
  296. };
  297. //! keying interface for crypto algorithms that take byte strings as keys
  298. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
  299. {
  300. public:
  301. virtual ~SimpleKeyingInterface() {}
  302. //! returns smallest valid key length in bytes */
  303. virtual size_t MinKeyLength() const =0;
  304. //! returns largest valid key length in bytes */
  305. virtual size_t MaxKeyLength() const =0;
  306. //! returns default (recommended) key length in bytes */
  307. virtual size_t DefaultKeyLength() const =0;
  308. //! returns the smallest valid key length in bytes that is >= min(n, GetMaxKeyLength())
  309. virtual size_t GetValidKeyLength(size_t n) const =0;
  310. //! returns whether n is a valid key length
  311. virtual bool IsValidKeyLength(size_t n) const
  312. {return n == GetValidKeyLength(n);}
  313. //! set or reset the key of this object
  314. /*! \param params is used to specify Rounds, BlockSize, etc. */
  315. virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
  316. //! calls SetKey() with an NameValuePairs object that just specifies "Rounds"
  317. void SetKeyWithRounds(const byte *key, size_t length, int rounds);
  318. //! calls SetKey() with an NameValuePairs object that just specifies "IV"
  319. void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
  320. //! calls SetKey() with an NameValuePairs object that just specifies "IV"
  321. void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
  322. {SetKeyWithIV(key, length, iv, IVSize());}
  323. enum IV_Requirement {UNIQUE_IV = 0, RANDOM_IV, UNPREDICTABLE_RANDOM_IV, INTERNALLY_GENERATED_IV, NOT_RESYNCHRONIZABLE};
  324. //! returns the minimal requirement for secure IVs
  325. virtual IV_Requirement IVRequirement() const =0;
  326. //! returns whether this object can be resynchronized (i.e. supports initialization vectors)
  327. /*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */
  328. bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
  329. //! returns whether this object can use random IVs (in addition to ones returned by GetNextIV)
  330. bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
  331. //! returns whether this object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV)
  332. bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
  333. //! returns whether this object can use structured IVs, for example a counter (in addition to ones returned by GetNextIV)
  334. bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
  335. virtual unsigned int IVSize() const {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
  336. //! returns default length of IVs accepted by this object
  337. unsigned int DefaultIVLength() const {return IVSize();}
  338. //! returns minimal length of IVs accepted by this object
  339. virtual unsigned int MinIVLength() const {return IVSize();}
  340. //! returns maximal length of IVs accepted by this object
  341. virtual unsigned int MaxIVLength() const {return IVSize();}
  342. //! resynchronize with an IV. ivLength=-1 means use IVSize()
  343. virtual void Resynchronize(const byte *iv, int ivLength=-1) {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
  344. //! get a secure IV for the next message
  345. /*! This method should be called after you finish encrypting one message and are ready to start the next one.
  346. After calling it, you must call SetKey() or Resynchronize() before using this object again.
  347. This method is not implemented on decryption objects. */
  348. virtual void GetNextIV(RandomNumberGenerator &rng, byte *IV);
  349. protected:
  350. virtual const Algorithm & GetAlgorithm() const =0;
  351. virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
  352. void ThrowIfInvalidKeyLength(size_t length);
  353. void ThrowIfResynchronizable(); // to be called when no IV is passed
  354. void ThrowIfInvalidIV(const byte *iv); // check for NULL IV if it can't be used
  355. size_t ThrowIfInvalidIVLength(int size);
  356. const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
  357. inline void AssertValidKeyLength(size_t length) const
  358. {assert(IsValidKeyLength(length));}
  359. };
  360. //! interface for the data processing part of block ciphers
  361. /*! Classes derived from BlockTransformation are block ciphers
  362. in ECB mode (for example the DES::Encryption class), which are stateless.
  363. These classes should not be used directly, but only in combination with
  364. a mode class (see CipherModeDocumentation in modes.h).
  365. */
  366. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
  367. {
  368. public:
  369. //! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock
  370. virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
  371. //! encrypt or decrypt one block
  372. /*! \pre size of inBlock and outBlock == BlockSize() */
  373. void ProcessBlock(const byte *inBlock, byte *outBlock) const
  374. {ProcessAndXorBlock(inBlock, NULL, outBlock);}
  375. //! encrypt or decrypt one block in place
  376. void ProcessBlock(byte *inoutBlock) const
  377. {ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);}
  378. //! block size of the cipher in bytes
  379. virtual unsigned int BlockSize() const =0;
  380. //! returns how inputs and outputs should be aligned for optimal performance
  381. virtual unsigned int OptimalDataAlignment() const;
  382. //! returns true if this is a permutation (i.e. there is an inverse transformation)
  383. virtual bool IsPermutation() const {return true;}
  384. //! returns true if this is an encryption object
  385. virtual bool IsForwardTransformation() const =0;
  386. //! return number of blocks that can be processed in parallel, for bit-slicing implementations
  387. virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
  388. enum {BT_InBlockIsCounter=1, BT_DontIncrementInOutPointers=2, BT_XorInput=4, BT_ReverseDirection=8, BT_AllowParallel=16} FlagsForAdvancedProcessBlocks;
  389. //! encrypt and xor blocks according to flags (see FlagsForAdvancedProcessBlocks)
  390. /*! /note If BT_InBlockIsCounter is set, last byte of inBlocks may be modified. */
  391. virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
  392. inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
  393. };
  394. //! interface for the data processing part of stream ciphers
  395. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
  396. {
  397. public:
  398. //! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
  399. StreamTransformation& Ref() {return *this;}
  400. //! returns block size, if input must be processed in blocks, otherwise 1
  401. virtual unsigned int MandatoryBlockSize() const {return 1;}
  402. //! returns the input block size that is most efficient for this cipher
  403. /*! \note optimal input length is n * OptimalBlockSize() - GetOptimalBlockSizeUsed() for any n > 0 */
  404. virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
  405. //! returns how much of the current block is used up
  406. virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
  407. //! returns how input should be aligned for optimal performance
  408. virtual unsigned int OptimalDataAlignment() const;
  409. //! encrypt or decrypt an array of bytes of specified length
  410. /*! \note either inString == outString, or they don't overlap */
  411. virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
  412. //! for ciphers where the last block of data is special, encrypt or decrypt the last block of data
  413. /*! For now the only use of this function is for CBC-CTS mode. */
  414. virtual void ProcessLastBlock(byte *outString, const byte *inString, size_t length);
  415. //! returns the minimum size of the last block, 0 indicating the last block is not special
  416. virtual unsigned int MinLastBlockSize() const {return 0;}
  417. //! same as ProcessData(inoutString, inoutString, length)
  418. inline void ProcessString(byte *inoutString, size_t length)
  419. {ProcessData(inoutString, inoutString, length);}
  420. //! same as ProcessData(outString, inString, length)
  421. inline void ProcessString(byte *outString, const byte *inString, size_t length)
  422. {ProcessData(outString, inString, length);}
  423. //! implemented as {ProcessData(&input, &input, 1); return input;}
  424. inline byte ProcessByte(byte input)
  425. {ProcessData(&input, &input, 1); return input;}
  426. //! returns whether this cipher supports random access
  427. virtual bool IsRandomAccess() const =0;
  428. //! for random access ciphers, seek to an absolute position
  429. virtual void Seek(lword n)
  430. {
  431. assert(!IsRandomAccess());
  432. throw NotImplemented("StreamTransformation: this object doesn't support random access");
  433. }
  434. //! returns whether this transformation is self-inverting (e.g. xor with a keystream)
  435. virtual bool IsSelfInverting() const =0;
  436. //! returns whether this is an encryption object
  437. virtual bool IsForwardTransformation() const =0;
  438. };
  439. //! interface for hash functions and data processing part of MACs
  440. /*! HashTransformation objects are stateful. They are created in an initial state,
  441. change state as Update() is called, and return to the initial
  442. state when Final() is called. This interface allows a large message to
  443. be hashed in pieces by calling Update() on each piece followed by
  444. calling Final().
  445. */
  446. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
  447. {
  448. public:
  449. //! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
  450. HashTransformation& Ref() {return *this;}
  451. //! process more input
  452. virtual void Update(const byte *input, size_t length) =0;
  453. //! request space to write input into
  454. virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULL;}
  455. //! compute hash for current message, then restart for a new message
  456. /*! \pre size of digest == DigestSize(). */
  457. virtual void Final(byte *digest)
  458. {TruncatedFinal(digest, DigestSize());}
  459. //! discard the current state, and restart with a new message
  460. virtual void Restart()
  461. {TruncatedFinal(NULL, 0);}
  462. //! size of the hash/digest/MAC returned by Final()
  463. virtual unsigned int DigestSize() const =0;
  464. //! same as DigestSize()
  465. unsigned int TagSize() const {return DigestSize();}
  466. //! block size of underlying compression function, or 0 if not block based
  467. virtual unsigned int BlockSize() const {return 0;}
  468. //! input to Update() should have length a multiple of this for optimal speed
  469. virtual unsigned int OptimalBlockSize() const {return 1;}
  470. //! returns how input should be aligned for optimal performance
  471. virtual unsigned int OptimalDataAlignment() const;
  472. //! use this if your input is in one piece and you don't want to call Update() and Final() separately
  473. virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
  474. {Update(input, length); Final(digest);}
  475. //! verify that digest is a valid digest for the current message, then reinitialize the object
  476. /*! Default implementation is to call Final() and do a bitwise comparison
  477. between its output and digest. */
  478. virtual bool Verify(const byte *digest)
  479. {return TruncatedVerify(digest, DigestSize());}
  480. //! use this if your input is in one piece and you don't want to call Update() and Verify() separately
  481. virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
  482. {Update(input, length); return Verify(digest);}
  483. //! truncated version of Final()
  484. virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
  485. //! truncated version of CalculateDigest()
  486. virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
  487. {Update(input, length); TruncatedFinal(digest, digestSize);}
  488. //! truncated version of Verify()
  489. virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
  490. //! truncated version of VerifyDigest()
  491. virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
  492. {Update(input, length); return TruncatedVerify(digest, digestLength);}
  493. protected:
  494. void ThrowIfInvalidTruncatedSize(size_t size) const;
  495. };
  496. typedef HashTransformation HashFunction;
  497. //! interface for one direction (encryption or decryption) of a block cipher
  498. /*! \note These objects usually should not be used directly. See BlockTransformation for more details. */
  499. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
  500. {
  501. protected:
  502. const Algorithm & GetAlgorithm() const {return *this;}
  503. };
  504. //! interface for one direction (encryption or decryption) of a stream cipher or cipher mode
  505. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
  506. {
  507. protected:
  508. const Algorithm & GetAlgorithm() const {return *this;}
  509. };
  510. //! interface for message authentication codes
  511. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
  512. {
  513. protected:
  514. const Algorithm & GetAlgorithm() const {return *this;}
  515. };
  516. //! interface for for one direction (encryption or decryption) of a stream cipher or block cipher mode with authentication
  517. /*! The StreamTransformation part of this interface is used to encrypt/decrypt the data, and the MessageAuthenticationCode part of this
  518. interface is used to input additional authenticated data (AAD, which is MAC'ed but not encrypted), and to generate/verify the MAC. */
  519. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
  520. {
  521. public:
  522. //! 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
  523. class BadState : public Exception
  524. {
  525. public:
  526. explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
  527. explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
  528. };
  529. //! the maximum length of AAD that can be input before the encrypted data
  530. virtual lword MaxHeaderLength() const =0;
  531. //! the maximum length of encrypted data
  532. virtual lword MaxMessageLength() const =0;
  533. //! the maximum length of AAD that can be input after the encrypted data
  534. virtual lword MaxFooterLength() const {return 0;}
  535. //! if this function returns true, SpecifyDataLengths() must be called before attempting to input data
  536. /*! This is the case for some schemes, such as CCM. */
  537. virtual bool NeedsPrespecifiedDataLengths() const {return false;}
  538. //! this function only needs to be called if NeedsPrespecifiedDataLengths() returns true
  539. void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
  540. //! encrypt and generate MAC in one call. will truncate MAC if macSize < TagSize()
  541. 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);
  542. //! decrypt and verify MAC in one call, returning true iff MAC is valid. will assume MAC is truncated if macLength < TagSize()
  543. 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);
  544. // redeclare this to avoid compiler ambiguity errors
  545. virtual std::string AlgorithmName() const =0;
  546. protected:
  547. const Algorithm & GetAlgorithm() const {return *static_cast<const MessageAuthenticationCode *>(this);}
  548. virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength) {}
  549. };
  550. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  551. typedef SymmetricCipher StreamCipher;
  552. #endif
  553. //! interface for random number generators
  554. /*! All return values are uniformly distributed over the range specified.
  555. */
  556. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
  557. {
  558. public:
  559. //! update RNG state with additional unpredictable values
  560. virtual void IncorporateEntropy(const byte *input, size_t length) {throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");}
  561. //! returns true if IncorporateEntropy is implemented
  562. virtual bool CanIncorporateEntropy() const {return false;}
  563. //! generate new random byte and return it
  564. virtual byte GenerateByte();
  565. //! generate new random bit and return it
  566. /*! Default implementation is to call GenerateByte() and return its lowest bit. */
  567. virtual unsigned int GenerateBit();
  568. //! generate a random 32 bit word in the range min to max, inclusive
  569. virtual word32 GenerateWord32(word32 a=0, word32 b=0xffffffffL);
  570. //! generate random array of bytes
  571. virtual void GenerateBlock(byte *output, size_t size);
  572. //! generate and discard n bytes
  573. virtual void DiscardBytes(size_t n);
  574. //! generate random bytes as input to a BufferedTransformation
  575. virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
  576. //! randomly shuffle the specified array, resulting permutation is uniformly distributed
  577. template <class IT> void Shuffle(IT begin, IT end)
  578. {
  579. for (; begin != end; ++begin)
  580. std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1));
  581. }
  582. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  583. byte GetByte() {return GenerateByte();}
  584. unsigned int GetBit() {return GenerateBit();}
  585. word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);}
  586. word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);}
  587. void GetBlock(byte *output, size_t size) {GenerateBlock(output, size);}
  588. #endif
  589. };
  590. //! returns a reference that can be passed to functions that ask for a RNG but doesn't actually use it
  591. CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
  592. class WaitObjectContainer;
  593. class CallStack;
  594. //! interface for objects that you can wait for
  595. class CRYPTOPP_NO_VTABLE Waitable
  596. {
  597. public:
  598. virtual ~Waitable() {}
  599. //! maximum number of wait objects that this object can return
  600. virtual unsigned int GetMaxWaitObjectCount() const =0;
  601. //! put wait objects into container
  602. /*! \param callStack is used for tracing no wait loops, example:
  603. something.GetWaitObjects(c, CallStack("my func after X", 0));
  604. - or in an outer GetWaitObjects() method that itself takes a callStack parameter:
  605. innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack)); */
  606. virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
  607. //! wait on this object
  608. /*! same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container */
  609. bool Wait(unsigned long milliseconds, CallStack const& callStack);
  610. };
  611. //! the default channel for BufferedTransformation, equal to the empty string
  612. // VALVE, don't use a real object here as a global, make it a basic type so construction
  613. // order doesn't screw us (Alfred)
  614. //extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
  615. extern CRYPTOPP_DLL const char *DEFAULT_CHANNEL;
  616. //! channel for additional authenticated data, equal to "AAD"
  617. extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
  618. //! interface for buffered transformations
  619. /*! BufferedTransformation is a generalization of BlockTransformation,
  620. StreamTransformation, and HashTransformation.
  621. A buffered transformation is an object that takes a stream of bytes
  622. as input (this may be done in stages), does some computation on them, and
  623. then places the result into an internal buffer for later retrieval. Any
  624. partial result already in the output buffer is not modified by further
  625. input.
  626. If a method takes a "blocking" parameter, and you
  627. pass "false" for it, the method will return before all input has been processed if
  628. the input cannot be processed without waiting (for network buffers to become available, for example).
  629. In this case the method will return true
  630. or a non-zero integer value. When this happens you must continue to call the method with the same
  631. parameters until it returns false or zero, before calling any other method on it or
  632. attached BufferedTransformation. The integer return value in this case is approximately
  633. the number of bytes left to be processed, and can be used to implement a progress bar.
  634. For functions that take a "propagation" parameter, propagation != 0 means pass on the signal to attached
  635. BufferedTransformation objects, with propagation decremented at each step until it reaches 0.
  636. -1 means unlimited propagation.
  637. \nosubgrouping
  638. */
  639. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
  640. {
  641. public:
  642. // placed up here for CW8
  643. static const std::string &NULL_CHANNEL; // same as DEFAULT_CHANNEL, for backwards compatibility
  644. BufferedTransformation() : Algorithm(false) {}
  645. //! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
  646. BufferedTransformation& Ref() {return *this;}
  647. //! \name INPUT
  648. //@{
  649. //! input a byte for processing
  650. size_t Put(byte inByte, bool blocking=true)
  651. {return Put(&inByte, 1, blocking);}
  652. //! input multiple bytes
  653. size_t Put(const byte *inString, size_t length, bool blocking=true)
  654. {return Put2(inString, length, 0, blocking);}
  655. //! input a 16-bit word
  656. size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  657. //! input a 32-bit word
  658. size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  659. //! request space which can be written into by the caller, and then used as input to Put()
  660. /*! \param size is requested size (as a hint) for input, and size of the returned space for output */
  661. /*! \note The purpose of this method is to help avoid doing extra memory allocations. */
  662. virtual byte * CreatePutSpace(size_t &size) {size=0; return NULL;}
  663. virtual bool CanModifyInput() const {return false;}
  664. //! input multiple bytes that may be modified by callee
  665. size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
  666. {return PutModifiable2(inString, length, 0, blocking);}
  667. bool MessageEnd(int propagation=-1, bool blocking=true)
  668. {return !!Put2(NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
  669. size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
  670. {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
  671. //! input multiple bytes for blocking or non-blocking processing
  672. /*! \param messageEnd means how many filters to signal MessageEnd to, including this one */
  673. virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
  674. //! input multiple bytes that may be modified by callee for blocking or non-blocking processing
  675. /*! \param messageEnd means how many filters to signal MessageEnd to, including this one */
  676. virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
  677. {return Put2(inString, length, messageEnd, blocking);}
  678. //! thrown by objects that have not implemented nonblocking input processing
  679. struct BlockingInputOnly : public NotImplemented
  680. {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
  681. //@}
  682. //! \name WAITING
  683. //@{
  684. unsigned int GetMaxWaitObjectCount() const;
  685. void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
  686. //@}
  687. //! \name SIGNALS
  688. //@{
  689. virtual void IsolatedInitialize(const NameValuePairs &parameters) {throw NotImplemented("BufferedTransformation: this object can't be reinitialized");}
  690. virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
  691. virtual bool IsolatedMessageSeriesEnd(bool blocking) {return false;}
  692. //! initialize or reinitialize this object
  693. virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
  694. //! flush buffered input and/or output
  695. /*! \param hardFlush is used to indicate whether all data should be flushed
  696. \note Hard flushes must be used with care. It means try to process and output everything, even if
  697. there may not be enough data to complete the action. For example, hard flushing a HexDecoder would
  698. cause an error if you do it after inputing an odd number of hex encoded characters.
  699. For some types of filters, for example ZlibDecompressor, hard flushes can only
  700. be done at "synchronization points". These synchronization points are positions in the data
  701. stream that are created by hard flushes on the corresponding reverse filters, in this
  702. example ZlibCompressor. This is useful when zlib compressed data is moved across a
  703. network in packets and compression state is preserved across packets, as in the ssh2 protocol.
  704. */
  705. virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
  706. //! mark end of a series of messages
  707. /*! There should be a MessageEnd immediately before MessageSeriesEnd. */
  708. virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
  709. //! set propagation of automatically generated and transferred signals
  710. /*! propagation == 0 means do not automaticly generate signals */
  711. virtual void SetAutoSignalPropagation(int propagation) {}
  712. //!
  713. virtual int GetAutoSignalPropagation() const {return 0;}
  714. public:
  715. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  716. void Close() {MessageEnd();}
  717. #endif
  718. //@}
  719. //! \name RETRIEVAL OF ONE MESSAGE
  720. //@{
  721. //! returns number of bytes that is currently ready for retrieval
  722. /*! All retrieval functions return the actual number of bytes
  723. retrieved, which is the lesser of the request number and
  724. MaxRetrievable(). */
  725. virtual lword MaxRetrievable() const;
  726. //! returns whether any bytes are currently ready for retrieval
  727. virtual bool AnyRetrievable() const;
  728. //! try to retrieve a single byte
  729. virtual size_t Get(byte &outByte);
  730. //! try to retrieve multiple bytes
  731. virtual size_t Get(byte *outString, size_t getMax);
  732. //! peek at the next byte without removing it from the output buffer
  733. virtual size_t Peek(byte &outByte) const;
  734. //! peek at multiple bytes without removing them from the output buffer
  735. virtual size_t Peek(byte *outString, size_t peekMax) const;
  736. //! try to retrieve a 16-bit word
  737. size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
  738. //! try to retrieve a 32-bit word
  739. size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
  740. //! try to peek at a 16-bit word
  741. size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
  742. //! try to peek at a 32-bit word
  743. size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
  744. //! move transferMax bytes of the buffered output to target as input
  745. lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
  746. {TransferTo2(target, transferMax, channel); return transferMax;}
  747. //! discard skipMax bytes from the output buffer
  748. virtual lword Skip(lword skipMax=LWORD_MAX);
  749. //! copy copyMax bytes of the buffered output to target as input
  750. lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
  751. {return CopyRangeTo(target, 0, copyMax, channel);}
  752. //! copy copyMax bytes of the buffered output, starting at position (relative to current position), to target as input
  753. lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
  754. {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
  755. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  756. unsigned long MaxRetrieveable() const {return MaxRetrievable();}
  757. #endif
  758. //@}
  759. //! \name RETRIEVAL OF MULTIPLE MESSAGES
  760. //@{
  761. //!
  762. virtual lword TotalBytesRetrievable() const;
  763. //! number of times MessageEnd() has been received minus messages retrieved or skipped
  764. virtual unsigned int NumberOfMessages() const;
  765. //! returns true if NumberOfMessages() > 0
  766. virtual bool AnyMessages() const;
  767. //! start retrieving the next message
  768. /*!
  769. Returns false if no more messages exist or this message
  770. is not completely retrieved.
  771. */
  772. virtual bool GetNextMessage();
  773. //! skip count number of messages
  774. virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
  775. //!
  776. unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
  777. {TransferMessagesTo2(target, count, channel); return count;}
  778. //!
  779. unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
  780. //!
  781. virtual void SkipAll();
  782. //!
  783. void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
  784. {TransferAllTo2(target, channel);}
  785. //!
  786. void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
  787. virtual bool GetNextMessageSeries() {return false;}
  788. virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
  789. virtual unsigned int NumberOfMessageSeries() const {return 0;}
  790. //@}
  791. //! \name NON-BLOCKING TRANSFER OF OUTPUT
  792. //@{
  793. //! upon return, byteCount contains number of bytes that have finished being transfered, and returns the number of bytes left in the current transfer block
  794. virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
  795. //! upon return, begin contains the start position of data yet to be finished copying, and returns the number of bytes left in the current transfer block
  796. virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
  797. //! upon return, messageCount contains number of messages that have finished being transfered, and returns the number of bytes left in the current transfer block
  798. size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
  799. //! returns the number of bytes left in the current transfer block
  800. size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
  801. //@}
  802. //! \name CHANNELS
  803. //@{
  804. struct NoChannelSupport : public NotImplemented
  805. {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
  806. struct InvalidChannelName : public InvalidArgument
  807. {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
  808. size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
  809. {return ChannelPut(channel, &inByte, 1, blocking);}
  810. size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
  811. {return ChannelPut2(channel, inString, length, 0, blocking);}
  812. size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
  813. {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
  814. size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  815. size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  816. bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
  817. {return !!ChannelPut2(channel, NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
  818. size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
  819. {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
  820. virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
  821. virtual size_t ChannelPut2(const std::string &channel, const byte *begin, size_t length, int messageEnd, bool blocking);
  822. virtual size_t ChannelPutModifiable2(const std::string &channel, byte *begin, size_t length, int messageEnd, bool blocking);
  823. virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
  824. virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
  825. virtual void SetRetrievalChannel(const std::string &channel);
  826. //@}
  827. //! \name ATTACHMENT
  828. /*! Some BufferedTransformation objects (e.g. Filter objects)
  829. allow other BufferedTransformation objects to be attached. When
  830. this is done, the first object instead of buffering its output,
  831. sents that output to the attached object as input. The entire
  832. attachment chain is deleted when the anchor object is destructed.
  833. */
  834. //@{
  835. //! returns whether this object allows attachment
  836. virtual bool Attachable() {return false;}
  837. //! returns the object immediately attached to this object or NULL for no attachment
  838. virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;}
  839. //!
  840. virtual const BufferedTransformation *AttachedTransformation() const
  841. {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
  842. //! delete the current attachment chain and replace it with newAttachment
  843. virtual void Detach(BufferedTransformation *newAttachment = 0)
  844. {assert(!Attachable()); throw NotImplemented("BufferedTransformation: this object is not attachable");}
  845. //! add newAttachment to the end of attachment chain
  846. virtual void Attach(BufferedTransformation *newAttachment);
  847. //@}
  848. protected:
  849. static int DecrementPropagation(int propagation)
  850. {return propagation != 0 ? propagation - 1 : 0;}
  851. private:
  852. byte m_buf[4]; // for ChannelPutWord16 and ChannelPutWord32, to ensure buffer isn't deallocated before non-blocking operation completes
  853. };
  854. //! returns a reference to a BufferedTransformation object that discards all input
  855. BufferedTransformation & TheBitBucket();
  856. //! interface for crypto material, such as public and private keys, and crypto parameters
  857. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
  858. {
  859. public:
  860. //! exception thrown when invalid crypto material is detected
  861. class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
  862. {
  863. public:
  864. explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
  865. };
  866. //! assign values from source to this object
  867. /*! \note This function can be used to create a public key from a private key. */
  868. virtual void AssignFrom(const NameValuePairs &source) =0;
  869. //! check this object for errors
  870. /*! \param level denotes the level of thoroughness:
  871. 0 - using this object won't cause a crash or exception (rng is ignored)
  872. 1 - this object will probably function (encrypt, sign, etc.) correctly (but may not check for weak keys and such)
  873. 2 - make sure this object will function correctly, and do reasonable security checks
  874. 3 - do checks that may take a long time
  875. \return true if the tests pass */
  876. virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
  877. //! throws InvalidMaterial if this object fails Validate() test
  878. virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
  879. {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
  880. // virtual std::vector<std::string> GetSupportedFormats(bool includeSaveOnly=false, bool includeLoadOnly=false);
  881. //! save key into a BufferedTransformation
  882. virtual void Save(BufferedTransformation &bt) const
  883. {throw NotImplemented("CryptoMaterial: this object does not support saving");}
  884. //! load key from a BufferedTransformation
  885. /*! \throws KeyingErr if decode fails
  886. \note Generally does not check that the key is valid.
  887. Call ValidateKey() or ThrowIfInvalidKey() to check that. */
  888. virtual void Load(BufferedTransformation &bt)
  889. {throw NotImplemented("CryptoMaterial: this object does not support loading");}
  890. //! \return whether this object supports precomputation
  891. virtual bool SupportsPrecomputation() const {return false;}
  892. //! do precomputation
  893. /*! The exact semantics of Precompute() is varies, but
  894. typically it means calculate a table of n objects
  895. that can be used later to speed up computation. */
  896. virtual void Precompute(unsigned int n)
  897. {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
  898. //! retrieve previously saved precomputation
  899. virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
  900. {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
  901. //! save precomputation for later use
  902. virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
  903. {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
  904. // for internal library use
  905. void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
  906. #if (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
  907. // Sun Studio 11/CC 5.8 workaround: it generates incorrect code when casting to an empty virtual base class
  908. char m_sunCCworkaround;
  909. #endif
  910. };
  911. //! interface for generatable crypto material, such as private keys and crypto parameters
  912. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
  913. {
  914. public:
  915. //! generate a random key or crypto parameters
  916. /*! \throws KeyingErr if algorithm parameters are invalid, or if a key can't be generated
  917. (e.g., if this is a public key object) */
  918. virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs)
  919. {throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");}
  920. //! calls the above function with a NameValuePairs object that just specifies "KeySize"
  921. void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
  922. };
  923. //! interface for public keys
  924. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
  925. {
  926. };
  927. //! interface for private keys
  928. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
  929. {
  930. };
  931. //! interface for crypto prameters
  932. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
  933. {
  934. };
  935. //! interface for asymmetric algorithms
  936. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
  937. {
  938. public:
  939. //! returns a reference to the crypto material used by this object
  940. virtual CryptoMaterial & AccessMaterial() =0;
  941. //! returns a const reference to the crypto material used by this object
  942. virtual const CryptoMaterial & GetMaterial() const =0;
  943. //! for backwards compatibility, calls AccessMaterial().Load(bt)
  944. void BERDecode(BufferedTransformation &bt)
  945. {AccessMaterial().Load(bt);}
  946. //! for backwards compatibility, calls GetMaterial().Save(bt)
  947. void DEREncode(BufferedTransformation &bt) const
  948. {GetMaterial().Save(bt);}
  949. };
  950. //! interface for asymmetric algorithms using public keys
  951. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
  952. {
  953. public:
  954. // VC60 workaround: no co-variant return type
  955. CryptoMaterial & AccessMaterial() {return AccessPublicKey();}
  956. const CryptoMaterial & GetMaterial() const {return GetPublicKey();}
  957. virtual PublicKey & AccessPublicKey() =0;
  958. virtual const PublicKey & GetPublicKey() const {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
  959. };
  960. //! interface for asymmetric algorithms using private keys
  961. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
  962. {
  963. public:
  964. CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
  965. const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
  966. virtual PrivateKey & AccessPrivateKey() =0;
  967. virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
  968. };
  969. //! interface for key agreement algorithms
  970. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
  971. {
  972. public:
  973. CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
  974. const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
  975. virtual CryptoParameters & AccessCryptoParameters() =0;
  976. virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
  977. };
  978. //! interface for public-key encryptors and decryptors
  979. /*! This class provides an interface common to encryptors and decryptors
  980. for querying their plaintext and ciphertext lengths.
  981. */
  982. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
  983. {
  984. public:
  985. virtual ~PK_CryptoSystem() {}
  986. //! maximum length of plaintext for a given ciphertext length
  987. /*! \note This function returns 0 if ciphertextLength is not valid (too long or too short). */
  988. virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
  989. //! calculate length of ciphertext given length of plaintext
  990. /*! \note This function returns 0 if plaintextLength is not valid (too long). */
  991. virtual size_t CiphertextLength(size_t plaintextLength) const =0;
  992. //! this object supports the use of the parameter with the given name
  993. /*! some possible parameter names: EncodingParameters, KeyDerivationParameters */
  994. virtual bool ParameterSupported(const char *name) const =0;
  995. //! return fixed ciphertext length, if one exists, otherwise return 0
  996. /*! \note "Fixed" here means length of ciphertext does not depend on length of plaintext.
  997. It usually does depend on the key length. */
  998. virtual size_t FixedCiphertextLength() const {return 0;}
  999. //! return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0
  1000. virtual size_t FixedMaxPlaintextLength() const {return 0;}
  1001. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1002. size_t MaxPlainTextLength(size_t cipherTextLength) const {return MaxPlaintextLength(cipherTextLength);}
  1003. size_t CipherTextLength(size_t plainTextLength) const {return CiphertextLength(plainTextLength);}
  1004. #endif
  1005. };
  1006. //! interface for public-key encryptors
  1007. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
  1008. {
  1009. public:
  1010. //! exception thrown when trying to encrypt plaintext of invalid length
  1011. class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
  1012. {
  1013. public:
  1014. InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
  1015. };
  1016. //! encrypt a byte string
  1017. /*! \pre CiphertextLength(plaintextLength) != 0 (i.e., plaintext isn't too long)
  1018. \pre size of ciphertext == CiphertextLength(plaintextLength)
  1019. */
  1020. virtual void Encrypt(RandomNumberGenerator &rng,
  1021. const byte *plaintext, size_t plaintextLength,
  1022. byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
  1023. //! create a new encryption filter
  1024. /*! \note The caller is responsible for deleting the returned pointer.
  1025. \note Encoding parameters should be passed in the "EP" channel.
  1026. */
  1027. virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
  1028. BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
  1029. };
  1030. //! interface for public-key decryptors
  1031. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
  1032. {
  1033. public:
  1034. //! decrypt a byte string, and return the length of plaintext
  1035. /*! \pre size of plaintext == MaxPlaintextLength(ciphertextLength) bytes.
  1036. \return the actual length of the plaintext, indication that decryption failed.
  1037. */
  1038. virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
  1039. const byte *ciphertext, size_t ciphertextLength,
  1040. byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
  1041. //! create a new decryption filter
  1042. /*! \note caller is responsible for deleting the returned pointer
  1043. */
  1044. virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
  1045. BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
  1046. //! decrypt a fixed size ciphertext
  1047. DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
  1048. {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
  1049. };
  1050. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1051. typedef PK_CryptoSystem PK_FixedLengthCryptoSystem;
  1052. typedef PK_Encryptor PK_FixedLengthEncryptor;
  1053. typedef PK_Decryptor PK_FixedLengthDecryptor;
  1054. #endif
  1055. //! interface for public-key signers and verifiers
  1056. /*! This class provides an interface common to signers and verifiers
  1057. for querying scheme properties.
  1058. */
  1059. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
  1060. {
  1061. public:
  1062. //! 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
  1063. class CRYPTOPP_DLL InvalidKeyLength : public Exception
  1064. {
  1065. public:
  1066. InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
  1067. };
  1068. //! 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
  1069. class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
  1070. {
  1071. public:
  1072. KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
  1073. };
  1074. virtual ~PK_SignatureScheme() {}
  1075. //! signature length if it only depends on the key, otherwise 0
  1076. virtual size_t SignatureLength() const =0;
  1077. //! maximum signature length produced for a given length of recoverable message part
  1078. virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const {return SignatureLength();}
  1079. //! length of longest message that can be recovered, or 0 if this signature scheme does not support message recovery
  1080. virtual size_t MaxRecoverableLength() const =0;
  1081. //! 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
  1082. virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
  1083. //! requires a random number generator to sign
  1084. /*! if this returns false, NullRNG() can be passed to functions that take RandomNumberGenerator & */
  1085. virtual bool IsProbabilistic() const =0;
  1086. //! whether or not a non-recoverable message part can be signed
  1087. virtual bool AllowNonrecoverablePart() const =0;
  1088. //! if this function returns true, during verification you must input the signature before the message, otherwise you can input it at anytime */
  1089. virtual bool SignatureUpfront() const {return false;}
  1090. //! whether you must input the recoverable part before the non-recoverable part during signing
  1091. virtual bool RecoverablePartFirst() const =0;
  1092. };
  1093. //! interface for accumulating messages to be signed or verified
  1094. /*! Only Update() should be called
  1095. on this class. No other functions inherited from HashTransformation should be called.
  1096. */
  1097. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
  1098. {
  1099. public:
  1100. //! should not be called on PK_MessageAccumulator
  1101. unsigned int DigestSize() const
  1102. {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
  1103. //! should not be called on PK_MessageAccumulator
  1104. void TruncatedFinal(byte *digest, size_t digestSize)
  1105. {throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");}
  1106. };
  1107. //! interface for public-key signers
  1108. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
  1109. {
  1110. public:
  1111. //! create a new HashTransformation to accumulate the message to be signed
  1112. virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
  1113. virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
  1114. //! sign and delete messageAccumulator (even in case of exception thrown)
  1115. /*! \pre size of signature == MaxSignatureLength()
  1116. \return actual signature length
  1117. */
  1118. virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
  1119. //! sign and restart messageAccumulator
  1120. /*! \pre size of signature == MaxSignatureLength()
  1121. \return actual signature length
  1122. */
  1123. virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
  1124. //! sign a message
  1125. /*! \pre size of signature == MaxSignatureLength()
  1126. \return actual signature length
  1127. */
  1128. virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
  1129. //! sign a recoverable message
  1130. /*! \pre size of signature == MaxSignatureLength(recoverableMessageLength)
  1131. \return actual signature length
  1132. */
  1133. virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
  1134. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
  1135. };
  1136. //! interface for public-key signature verifiers
  1137. /*! The Recover* functions throw NotImplemented if the signature scheme does not support
  1138. message recovery.
  1139. The Verify* functions throw InvalidDataFormat if the scheme does support message
  1140. recovery and the signature contains a non-empty recoverable message part. The
  1141. Recovery* functions should be used in that case.
  1142. */
  1143. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
  1144. {
  1145. public:
  1146. //! create a new HashTransformation to accumulate the message to be verified
  1147. virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
  1148. //! input signature into a message accumulator
  1149. virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
  1150. //! check whether messageAccumulator contains a valid signature and message, and delete messageAccumulator (even in case of exception thrown)
  1151. virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
  1152. //! check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
  1153. virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
  1154. //! check whether input signature is a valid signature for input message
  1155. virtual bool VerifyMessage(const byte *message, size_t messageLen,
  1156. const byte *signature, size_t signatureLength) const;
  1157. //! recover a message from its signature
  1158. /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
  1159. */
  1160. virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
  1161. //! recover a message from its signature
  1162. /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
  1163. */
  1164. virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
  1165. //! recover a message from its signature
  1166. /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
  1167. */
  1168. virtual DecodingResult RecoverMessage(byte *recoveredMessage,
  1169. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
  1170. const byte *signature, size_t signatureLength) const;
  1171. };
  1172. //! interface for domains of simple key agreement protocols
  1173. /*! A key agreement domain is a set of parameters that must be shared
  1174. by two parties in a key agreement protocol, along with the algorithms
  1175. for generating key pairs and deriving agreed values.
  1176. */
  1177. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
  1178. {
  1179. public:
  1180. //! return length of agreed value produced
  1181. virtual unsigned int AgreedValueLength() const =0;
  1182. //! return length of private keys in this domain
  1183. virtual unsigned int PrivateKeyLength() const =0;
  1184. //! return length of public keys in this domain
  1185. virtual unsigned int PublicKeyLength() const =0;
  1186. //! generate private key
  1187. /*! \pre size of privateKey == PrivateKeyLength() */
  1188. virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  1189. //! generate public key
  1190. /*! \pre size of publicKey == PublicKeyLength() */
  1191. virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  1192. //! generate private/public key pair
  1193. /*! \note equivalent to calling GeneratePrivateKey() and then GeneratePublicKey() */
  1194. virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  1195. //! derive agreed value from your private key and couterparty's public key, return false in case of failure
  1196. /*! \note If you have previously validated the public key, use validateOtherPublicKey=false to save time.
  1197. \pre size of agreedValue == AgreedValueLength()
  1198. \pre length of privateKey == PrivateKeyLength()
  1199. \pre length of otherPublicKey == PublicKeyLength()
  1200. */
  1201. virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
  1202. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1203. bool ValidateDomainParameters(RandomNumberGenerator &rng) const
  1204. {return GetCryptoParameters().Validate(rng, 2);}
  1205. #endif
  1206. };
  1207. //! interface for domains of authenticated key agreement protocols
  1208. /*! In an authenticated key agreement protocol, each party has two
  1209. key pairs. The long-lived key pair is called the static key pair,
  1210. and the short-lived key pair is called the ephemeral key pair.
  1211. */
  1212. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
  1213. {
  1214. public:
  1215. //! return length of agreed value produced
  1216. virtual unsigned int AgreedValueLength() const =0;
  1217. //! return length of static private keys in this domain
  1218. virtual unsigned int StaticPrivateKeyLength() const =0;
  1219. //! return length of static public keys in this domain
  1220. virtual unsigned int StaticPublicKeyLength() const =0;
  1221. //! generate static private key
  1222. /*! \pre size of privateKey == PrivateStaticKeyLength() */
  1223. virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  1224. //! generate static public key
  1225. /*! \pre size of publicKey == PublicStaticKeyLength() */
  1226. virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  1227. //! generate private/public key pair
  1228. /*! \note equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey() */
  1229. virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  1230. //! return length of ephemeral private keys in this domain
  1231. virtual unsigned int EphemeralPrivateKeyLength() const =0;
  1232. //! return length of ephemeral public keys in this domain
  1233. virtual unsigned int EphemeralPublicKeyLength() const =0;
  1234. //! generate ephemeral private key
  1235. /*! \pre size of privateKey == PrivateEphemeralKeyLength() */
  1236. virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  1237. //! generate ephemeral public key
  1238. /*! \pre size of publicKey == PublicEphemeralKeyLength() */
  1239. virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  1240. //! generate private/public key pair
  1241. /*! \note equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() */
  1242. virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  1243. //! derive agreed value from your private keys and couterparty's public keys, return false in case of failure
  1244. /*! \note The ephemeral public key will always be validated.
  1245. If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time.
  1246. \pre size of agreedValue == AgreedValueLength()
  1247. \pre length of staticPrivateKey == StaticPrivateKeyLength()
  1248. \pre length of ephemeralPrivateKey == EphemeralPrivateKeyLength()
  1249. \pre length of staticOtherPublicKey == StaticPublicKeyLength()
  1250. \pre length of ephemeralOtherPublicKey == EphemeralPublicKeyLength()
  1251. */
  1252. virtual bool Agree(byte *agreedValue,
  1253. const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
  1254. const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
  1255. bool validateStaticOtherPublicKey=true) const =0;
  1256. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1257. bool ValidateDomainParameters(RandomNumberGenerator &rng) const
  1258. {return GetCryptoParameters().Validate(rng, 2);}
  1259. #endif
  1260. };
  1261. // interface for password authenticated key agreement protocols, not implemented yet
  1262. #if 0
  1263. //! interface for protocol sessions
  1264. /*! The methods should be called in the following order:
  1265. InitializeSession(rng, parameters); // or call initialize method in derived class
  1266. while (true)
  1267. {
  1268. if (OutgoingMessageAvailable())
  1269. {
  1270. length = GetOutgoingMessageLength();
  1271. GetOutgoingMessage(message);
  1272. ; // send outgoing message
  1273. }
  1274. if (LastMessageProcessed())
  1275. break;
  1276. ; // receive incoming message
  1277. ProcessIncomingMessage(message);
  1278. }
  1279. ; // call methods in derived class to obtain result of protocol session
  1280. */
  1281. class ProtocolSession
  1282. {
  1283. public:
  1284. //! exception thrown when an invalid protocol message is processed
  1285. class ProtocolError : public Exception
  1286. {
  1287. public:
  1288. ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
  1289. };
  1290. //! exception thrown when a function is called unexpectedly
  1291. /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
  1292. class UnexpectedMethodCall : public Exception
  1293. {
  1294. public:
  1295. UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
  1296. };
  1297. ProtocolSession() : m_rng(NULL), m_throwOnProtocolError(true), m_validState(false) {}
  1298. virtual ~ProtocolSession() {}
  1299. virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
  1300. bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
  1301. void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
  1302. bool HasValidState() const {return m_validState;}
  1303. virtual bool OutgoingMessageAvailable() const =0;
  1304. virtual unsigned int GetOutgoingMessageLength() const =0;
  1305. virtual void GetOutgoingMessage(byte *message) =0;
  1306. virtual bool LastMessageProcessed() const =0;
  1307. virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
  1308. protected:
  1309. void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
  1310. void CheckAndHandleInvalidState() const;
  1311. void SetValidState(bool valid) {m_validState = valid;}
  1312. RandomNumberGenerator *m_rng;
  1313. private:
  1314. bool m_throwOnProtocolError, m_validState;
  1315. };
  1316. class KeyAgreementSession : public ProtocolSession
  1317. {
  1318. public:
  1319. virtual unsigned int GetAgreedValueLength() const =0;
  1320. virtual void GetAgreedValue(byte *agreedValue) const =0;
  1321. };
  1322. class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
  1323. {
  1324. public:
  1325. void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
  1326. const byte *myId, unsigned int myIdLength,
  1327. const byte *counterPartyId, unsigned int counterPartyIdLength,
  1328. const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
  1329. };
  1330. class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
  1331. {
  1332. public:
  1333. //! return whether the domain parameters stored in this object are valid
  1334. virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
  1335. {return GetCryptoParameters().Validate(rng, 2);}
  1336. virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
  1337. virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
  1338. enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
  1339. virtual bool IsValidRole(unsigned int role) =0;
  1340. virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
  1341. };
  1342. #endif
  1343. //! BER Decode Exception Class, may be thrown during an ASN1 BER decode operation
  1344. class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
  1345. {
  1346. public:
  1347. BERDecodeErr() : InvalidArgument("BER decode error") {}
  1348. BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
  1349. };
  1350. //! interface for encoding and decoding ASN1 objects
  1351. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
  1352. {
  1353. public:
  1354. virtual ~ASN1Object() {}
  1355. //! decode this object from a BufferedTransformation, using BER (Basic Encoding Rules)
  1356. virtual void BERDecode(BufferedTransformation &bt) =0;
  1357. //! encode this object into a BufferedTransformation, using DER (Distinguished Encoding Rules)
  1358. virtual void DEREncode(BufferedTransformation &bt) const =0;
  1359. //! encode this object into a BufferedTransformation, using BER
  1360. /*! this may be useful if DEREncode() would be too inefficient */
  1361. virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
  1362. };
  1363. #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
  1364. typedef PK_SignatureScheme PK_SignatureSystem;
  1365. typedef SimpleKeyAgreementDomain PK_SimpleKeyAgreementDomain;
  1366. typedef AuthenticatedKeyAgreementDomain PK_AuthenticatedKeyAgreementDomain;
  1367. #endif
  1368. NAMESPACE_END
  1369. #endif