Crypto++  8.2
Free C++ class library of cryptographic schemes
cryptlib.h
Go to the documentation of this file.
1 // cryptlib.h - originally written and placed in the public domain by Wei Dai
2 
3 /// \file cryptlib.h
4 /// \brief Abstract base classes that provide a uniform interface to this library.
5 
6 /*! \mainpage Crypto++ Library 8.2 API Reference
7 <dl>
8 <dt>Abstract Base Classes<dd>
9  cryptlib.h
10 <dt>Authenticated Encryption Modes<dd>
11  CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)"
12 <dt>Block Ciphers<dd>
13  \ref Rijndael "AES", ARIA, Weak::ARC4, Blowfish, BTEA, \ref CHAM128 "CHAM (64/128)", Camellia,
14  \ref CAST128 "CAST (128/256)", DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES",
15  \ref DES_XEX3 "DESX", GOST, HIGHT, IDEA, LEA, \ref LR "Luby-Rackoff", \ref Kalyna128 "Kalyna (128/256/512)",
16  MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent,
17  \ref SHACAL2 "SHACAL-2", SHARK, \ref SIMECK64 "SIMECK (32/64)" SKIPJACK, SM4, Square, TEA,
18  \ref ThreeWay "3-Way", \ref Threefish256 "Threefish (256/512/1024)", Twofish, XTEA
19 <dt>Stream Ciphers<dd>
20  \ref ChaCha "ChaCha (8/12/20)", \ref HC128 "HC-128/256", \ref Panama "Panama-LE", \ref Panama "Panama-BE",
21  Rabbit, Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20
22 <dt>Hash Functions<dd>
23  BLAKE2s, BLAKE2b, \ref Keccak "Keccak (F1600)", SHA1, SHA224, SHA256, SHA384, SHA512,
24  \ref SHA3 "SHA-3", SM3, Tiger, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, SipHash, Whirlpool,
25  Weak::MD2, Weak::MD4, Weak::MD5
26 <dt>Non-Cryptographic Checksums<dd>
27  CRC32, CRC32C, Adler32
28 <dt>Message Authentication Codes<dd>
29  BLAKE2b, BLAKE2s, CBC_MAC, CMAC, DMAC, \ref GCM "GCM (GMAC)", HMAC, Poly1305, TTMAC, VMAC
30 <dt>Random Number Generators<dd>
31  NullRNG, LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG,
32  NIST Hash_DRBG and HMAC_DRBG, \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)",
33  DARN, RDRAND, RDSEED
34 <dt>Key Derivation and Password-based Cryptography<dd>
35  HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)",
36  \ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)"
37 <dt>Public Key Cryptosystems<dd>
38  DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
39 <dt>Public Key Signature Schemes<dd>
40  DSA, DSA2, \ref ed25519 "Ed25519", GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO,
41  RabinSS, RWSS, ESIGN
42 <dt>Key Agreement<dd>
43  DH, DH2, \ref x25519 "X25519", \ref MQV_Domain "MQV", \ref HMQV_Domain "HMQV",
44  \ref FHMQV_Domain "FHMQV", ECDH, x25519, ECMQV, ECHMQV, ECFHMQV, XTR_DH
45 <dt>Algebraic Structures<dd>
46  Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
47  ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP
48 <dt>Secret Sharing and Information Dispersal<dd>
49  SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
50 <dt>Compression<dd>
51  Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
52 <dt>Input Source Classes<dd>
53  StringSource, ArraySource, VectorSource, FileSource, RandomNumberSource
54 <dt>Output Sink Classes<dd>
55  StringSinkTemplate, StringSink, VectorSink, ArraySink, FileSink, RandomNumberSink
56 <dt>Filter Wrappers<dd>
57  StreamTransformationFilter, AuthenticatedEncryptionFilter, AuthenticatedDecryptionFilter, HashFilter,
58  HashVerificationFilter, SignerFilter, SignatureVerificationFilter
59 <dt>Binary to Text Encoders and Decoders<dd>
60  HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder,
61  Base32Decoder
62 <dt>Wrappers for OS features<dd>
63  Timer, ThreadUserTimer
64 
65 </dl>
66 
67 <!--
68 
69 <dt>FIPS 140 validated cryptography<dd>
70  fips140.h
71 
72 In the DLL version of Crypto++, only the following implementation class are available.
73 <dl>
74 <dt>Block Ciphers<dd>
75  AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK
76 <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
77  \ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>",
78  \ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>"
79 <dt>Hash Functions<dd>
80  SHA1, SHA224, SHA256, SHA384, SHA512
81 <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
82  RSASS<PKCS1v15, H>, RSASS<PSS, H>, RSASS_ISO<H>, RWSS<P1363_EMSA2, H>, DSA, ECDSA<ECP, H>,
83  ECDSA<EC2N, H>
84 <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
85  HMAC<H>, CBC_MAC<DES_EDE2>, CBC_MAC<DES_EDE3>, GCM<AES>
86 <dt>Random Number Generators<dd>
87  DefaultAutoSeededRNG (AutoSeededX917RNG<AES>)
88 <dt>Key Agreement<dd>
89  DH, DH2
90 <dt>Public Key Cryptosystems<dd>
91  RSAES<OAEP<SHA1> >
92 </dl>
93 
94 -->
95 
96 <p>This reference manual is a work in progress. Some classes lack detailed descriptions.
97 <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
98 <p>Thanks to Ryan Phillips for providing the Doxygen configuration file
99 and getting us started on the manual.
100 */
101 
102 #ifndef CRYPTOPP_CRYPTLIB_H
103 #define CRYPTOPP_CRYPTLIB_H
104 
105 #include "config.h"
106 #include "stdcpp.h"
107 #include "trap.h"
108 
109 #if CRYPTOPP_MSC_VERSION
110 # pragma warning(push)
111 # pragma warning(disable: 4127 4189 4505 4702)
112 #endif
113 
114 NAMESPACE_BEGIN(CryptoPP)
115 
116 // forward declarations
117 class Integer;
120 
121 /// \brief Specifies a direction for a cipher to operate
122 /// \sa BlockTransformation::IsForwardTransformation(), BlockTransformation::IsPermutation(), BlockTransformation::GetCipherDirection()
123 enum CipherDir {
124  /// \brief the cipher is performing encryption
126  /// \brief the cipher is performing decryption
128 
129 /// \brief Represents infinite time
130 const unsigned long INFINITE_TIME = ULONG_MAX;
131 
132 // VC60 workaround: using enums as template parameters causes problems
133 /// \brief Converts an enumeration to a type suitable for use as a template parameter
134 template <typename ENUM_TYPE, int VALUE>
136 {
137  static ENUM_TYPE ToEnum() {return static_cast<ENUM_TYPE>(VALUE);}
138 };
139 
140 /// \brief Provides the byte ordering
141 /// \details Big-endian and little-endian modes are supported. Bi-endian and PDP-endian modes
142 /// are not supported.
143 enum ByteOrder {
144  /// \brief byte order is little-endian
146  /// \brief byte order is big-endian
148 
149 /// \brief Provides a constant for LittleEndian
151 /// \brief Provides a constant for BigEndian
153 
154 /// \brief Base class for all exceptions thrown by the library
155 /// \details All library exceptions directly or indirectly inherit from the Exception class.
156 /// The Exception class itself inherits from std::exception. The library does not use
157 /// std::runtime_error derived classes.
158 class CRYPTOPP_DLL Exception : public std::exception
159 {
160 public:
161  /// \enum ErrorType
162  /// \brief Error types or categories
163  enum ErrorType {
164  /// \brief A method was called which was not implemented
166  /// \brief An invalid argument was detected
168  /// \brief BufferedTransformation received a Flush(true) signal but can't flush buffers
170  /// \brief Data integerity check, such as CRC or MAC, failed
172  /// \brief Input data was received that did not conform to expected format
174  /// \brief Error reading from input device or writing to output device
176  /// \brief Some other error occurred not belonging to other categories
177  OTHER_ERROR
178  };
179 
180  virtual ~Exception() throw() {}
181 
182  /// \brief Construct a new Exception
183  explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
184 
185  /// \brief Retrieves a C-string describing the exception
186  const char *what() const throw() {return (m_what.c_str());}
187  /// \brief Retrieves a string describing the exception
188  const std::string &GetWhat() const {return m_what;}
189  /// \brief Sets the error string for the exception
190  void SetWhat(const std::string &s) {m_what = s;}
191  /// \brief Retrieves the error type for the exception
192  ErrorType GetErrorType() const {return m_errorType;}
193  /// \brief Sets the error type for the exceptions
194  void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
195 
196 private:
197  ErrorType m_errorType;
198  std::string m_what;
199 };
200 
201 /// \brief An invalid argument was detected
202 class CRYPTOPP_DLL InvalidArgument : public Exception
203 {
204 public:
205  /// \brief Construct an InvalidArgument
206  /// \param s the message for the exception
207  /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
208  explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
209 };
210 
211 /// \brief Input data was received that did not conform to expected format
212 class CRYPTOPP_DLL InvalidDataFormat : public Exception
213 {
214 public:
215  /// \brief Construct an InvalidDataFormat
216  /// \param s the message for the exception
217  /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
218  explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
219 };
220 
221 /// \brief A decryption filter encountered invalid ciphertext
222 class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
223 {
224 public:
225  /// \brief Construct an InvalidCiphertext
226  /// \param s the message for the exception
227  /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
228  explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
229 };
230 
231 /// \brief A method was called which was not implemented
232 class CRYPTOPP_DLL NotImplemented : public Exception
233 {
234 public:
235  /// \brief Construct an NotImplemented
236  /// \param s the message for the exception
237  /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
238  explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
239 };
240 
241 /// \brief Flush(true) was called but it can't completely flush its buffers
242 class CRYPTOPP_DLL CannotFlush : public Exception
243 {
244 public:
245  /// \brief Construct an CannotFlush
246  /// \param s the message for the exception
247  /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
248  explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
249 };
250 
251 /// \brief The operating system reported an error
252 class CRYPTOPP_DLL OS_Error : public Exception
253 {
254 public:
255  virtual ~OS_Error() throw() {}
256 
257  /// \brief Construct an OS_Error
258  /// \param errorType the error type
259  /// \param s the message for the exception
260  /// \param operation the operation for the exception
261  /// \param errorCode the error code
262  /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
263  OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
264  : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
265 
266  /// \brief Retrieve the operating system API that reported the error
267  const std::string & GetOperation() const {return m_operation;}
268  /// \brief Retrieve the error code returned by the operating system
269  int GetErrorCode() const {return m_errorCode;}
270 
271 protected:
272  std::string m_operation;
273  int m_errorCode;
274 };
275 
276 /// \brief Returns a decoding results
277 struct CRYPTOPP_DLL DecodingResult
278 {
279  /// \brief Constructs a DecodingResult
280  /// \details isValidCoding is initialized to false and messageLength is
281  /// initialized to 0.
282  explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
283  /// \brief Constructs a DecodingResult
284  /// \param len the message length
285  /// \details isValidCoding is initialized to true.
286  explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
287 
288  /// \brief Compare two DecodingResult
289  /// \param rhs the other DecodingResult
290  /// \return true if either isValidCoding or messageLength is \a not equal,
291  /// false otherwise
292  bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
293  /// \brief Compare two DecodingResult
294  /// \param rhs the other DecodingResult
295  /// \return true if either isValidCoding or messageLength is \a not equal,
296  /// false otherwise
297  /// \details Returns <tt>!operator==(rhs)</tt>.
298  bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
299 
300  /// \brief Flag to indicate the decoding is valid
302  /// \brief Recovered message length if isValidCoding is true, undefined otherwise
304 };
305 
306 /// \brief Interface for retrieving values given their names
307 /// \details This class is used to safely pass a variable number of arbitrarily
308 /// typed arguments to functions and to read values from keys and crypto parameters.
309 /// \details To obtain an object that implements NameValuePairs for the purpose of
310 /// parameter passing, use the MakeParameters() function.
311 /// \details To get a value from NameValuePairs, you need to know the name and the
312 /// type of the value. Call GetValueNames() on a NameValuePairs object to obtain a
313 /// list of value names that it supports. then look at the Name namespace
314 /// documentation to see what the type of each value is, or alternatively, call
315 /// GetIntValue() with the value name, and if the type is not int, a
316 /// ValueTypeMismatch exception will be thrown and you can get the actual type from
317 /// the exception object.
318 /// \sa NullNameValuePairs, g_nullNameValuePairs,
319 /// <A HREF="http://www.cryptopp.com/wiki/NameValuePairs">NameValuePairs</A> on the
320 /// Crypto++ wiki
322 {
323 public:
324  virtual ~NameValuePairs() {}
325 
326  /// \brief Thrown when an unexpected type is encountered
327  /// \details Exception thrown when trying to retrieve a value using a different
328  /// type than expected
329  class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
330  {
331  public:
332  /// \brief Construct a ValueTypeMismatch
333  /// \param name the name of the value
334  /// \param stored the \a actual type of the value stored
335  /// \param retrieving the \a presumed type of the value retrieved
336  ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
337  : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
338  , m_stored(stored), m_retrieving(retrieving) {}
339 
340  /// \brief Provides the stored type
341  /// \return the C++ mangled name of the type
342  const std::type_info & GetStoredTypeInfo() const {return m_stored;}
343 
344  /// \brief Provides the retrieveing type
345  /// \return the C++ mangled name of the type
346  const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
347 
348  private:
349  const std::type_info &m_stored;
350  const std::type_info &m_retrieving;
351  };
352 
353  /// \brief Get a copy of this object or subobject
354  /// \tparam T class or type
355  /// \param object reference to a variable that receives the value
356  template <class T>
357  bool GetThisObject(T &object) const
358  {
359  return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
360  }
361 
362  /// \brief Get a pointer to this object
363  /// \tparam T class or type
364  /// \param ptr reference to a pointer to a variable that receives the value
365  template <class T>
366  bool GetThisPointer(T *&ptr) const
367  {
368  return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr);
369  }
370 
371  /// \brief Get a named value
372  /// \tparam T class or type
373  /// \param name the name of the object or value to retrieve
374  /// \param value reference to a variable that receives the value
375  /// \returns true if the value was retrieved, false otherwise
376  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
377  /// GetRequiredParameter() and GetRequiredIntParameter()
378  template <class T>
379  bool GetValue(const char *name, T &value) const
380  {
381  return GetVoidValue(name, typeid(T), &value);
382  }
383 
384  /// \brief Get a named value
385  /// \tparam T class or type
386  /// \param name the name of the object or value to retrieve
387  /// \param defaultValue the default value of the class or type if it does not exist
388  /// \return the object or value
389  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
390  /// GetRequiredParameter() and GetRequiredIntParameter()
391  template <class T>
392  T GetValueWithDefault(const char *name, T defaultValue) const
393  {
394  T value;
395  bool result = GetValue(name, value);
396  // No assert... this recovers from failure
397  if (result) {return value;}
398  return defaultValue;
399  }
400 
401  /// \brief Get a list of value names that can be retrieved
402  /// \return a list of names available to retrieve
403  /// \details the items in the list are delimited with a colon.
404  CRYPTOPP_DLL std::string GetValueNames() const
405  {std::string result; GetValue("ValueNames", result); return result;}
406 
407  /// \brief Get a named value with type int
408  /// \param name the name of the value to retrieve
409  /// \param value the value retrieved upon success
410  /// \return true if an int value was retrieved, false otherwise
411  /// \details GetIntValue() is used to ensure we don't accidentally try to get an
412  /// unsigned int or some other type when we mean int (which is the most common case)
413  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
414  /// GetRequiredParameter() and GetRequiredIntParameter()
415  CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
416  {return GetValue(name, value);}
417 
418  /// \brief Get a named value with type int, with default
419  /// \param name the name of the value to retrieve
420  /// \param defaultValue the default value if the name does not exist
421  /// \return the value retrieved on success or the default value
422  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
423  /// GetRequiredParameter() and GetRequiredIntParameter()
424  CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
425  {return GetValueWithDefault(name, defaultValue);}
426 
427  /// \brief Get a named value with type word64
428  /// \param name the name of the value to retrieve
429  /// \param value the value retrieved upon success
430  /// \return true if an word64 value was retrieved, false otherwise
431  /// \sa GetValue(), GetValueWithDefault(), GetWord64ValueWithDefault(), GetIntValue(),
432  /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredIntParameter()
433  CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const
434  {return GetValue(name, value);}
435 
436  /// \brief Get a named value with type word64, with default
437  /// \param name the name of the value to retrieve
438  /// \param defaultValue the default value if the name does not exist
439  /// \return the value retrieved on success or the default value
440  /// \sa GetValue(), GetValueWithDefault(), GetWord64Value(), GetIntValue(),
441  /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredWord64Parameter()
442  CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
443  {return GetValueWithDefault(name, defaultValue);}
444 
445  /// \brief Ensures an expected name and type is present
446  /// \param name the name of the value
447  /// \param stored the type that was stored for the name
448  /// \param retrieving the type that is being retrieved for the name
449  /// \throws ValueTypeMismatch
450  /// \details ThrowIfTypeMismatch() effectively performs a type safety check.
451  /// stored and retrieving are C++ mangled names for the type.
452  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
453  /// GetRequiredParameter() and GetRequiredIntParameter()
454  CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
455  {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
456 
457  /// \brief Retrieves a required name/value pair
458  /// \tparam T class or type
459  /// \param className the name of the class
460  /// \param name the name of the value
461  /// \param value reference to a variable to receive the value
462  /// \throws InvalidArgument
463  /// \details GetRequiredParameter() throws InvalidArgument if the name
464  /// is not present or not of the expected type T.
465  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
466  /// GetRequiredParameter() and GetRequiredIntParameter()
467  template <class T>
468  void GetRequiredParameter(const char *className, const char *name, T &value) const
469  {
470  if (!GetValue(name, value))
471  throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
472  }
473 
474  /// \brief Retrieves a required name/value pair
475  /// \param className the name of the class
476  /// \param name the name of the value
477  /// \param value reference to a variable to receive the value
478  /// \throws InvalidArgument
479  /// \details GetRequiredParameter() throws InvalidArgument if the name
480  /// is not present or not of the expected type T.
481  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
482  /// GetRequiredParameter() and GetRequiredIntParameter()
483  CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
484  {
485  if (!GetIntValue(name, value))
486  throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
487  }
488 
489  /// \brief Get a named value
490  /// \param name the name of the object or value to retrieve
491  /// \param valueType reference to a variable that receives the value
492  /// \param pValue void pointer to a variable that receives the value
493  /// \returns true if the value was retrieved, false otherwise
494  /// \details GetVoidValue() retrieves the value of name if it exists.
495  /// \note GetVoidValue() is an internal function and should be implemented
496  /// by derived classes. Users should use one of the other functions instead.
497  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
498  /// GetRequiredParameter() and GetRequiredIntParameter()
499  CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
500 };
501 
502 // Doxygen cannot handle initialization
503 #if CRYPTOPP_DOXYGEN_PROCESSING
504 /// \brief Default channel for BufferedTransformation
505 /// \details DEFAULT_CHANNEL is equal to an empty string
506 /// \details The definition for DEFAULT_CHANNEL is in <tt>cryptlib.cpp</tt>.
507 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
508 /// Initialization Order Fiasco</A>. If you experience a crash in
509 /// DEFAULT_CHANNEL where the string object is NULL, then you probably have
510 /// a global object using DEFAULT_CHANNEL before it has been constructed.
511 const std::string DEFAULT_CHANNEL;
512 
513 /// \brief Channel for additional authenticated data
514 /// \details AAD_CHANNEL is equal to "AAD"
515 /// \details The definition for AAD_CHANNEL is in <tt>cryptlib.cpp</tt>.
516 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
517 /// Initialization Order Fiasco</A>. If you experience a crash in
518 /// AAD_CHANNEL where the string object is NULL, then you probably have a
519 /// global object using AAD_CHANNEL before it has been constructed.
520 const std::string AAD_CHANNEL;
521 
522 /// \brief An empty set of name-value pairs
523 /// \details The definition for g_nullNameValuePairs is in <tt>cryptlib.cpp</tt>.
524 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
525 /// Initialization Order Fiasco</A>. If you experience a crash in
526 /// g_nullNameValuePairs where the string object is NULL, then you probably
527 /// have a global object using g_nullNameValuePairs before it has been
528 /// constructed.
530 
531 #else
532 extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
533 extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
534 extern CRYPTOPP_DLL const NameValuePairs& g_nullNameValuePairs;
535 #endif
536 
537 // Document additional name spaces which show up elsewhere in the sources.
538 #if CRYPTOPP_DOXYGEN_PROCESSING
539 /// \brief Namespace containing value name definitions.
540 /// \details Name is part of the CryptoPP namespace.
541 /// \details The semantics of value names, types are:
542 /// <pre>
543 /// ThisObject:ClassName (ClassName, copy of this object or a subobject)
544 /// ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
545 /// </pre>
546 DOCUMENTED_NAMESPACE_BEGIN(Name)
547 // more names defined in argnames.h
548 DOCUMENTED_NAMESPACE_END
549 
550 /// \brief Namespace containing weak and wounded algorithms.
551 /// \details Weak is part of the CryptoPP namespace. Schemes and algorithms are moved into Weak
552 /// when their security level is reduced to an unacceptable level by contemporary standards.
553 /// \details To use an algorithm in the Weak namespace, you must <tt>\c \#define
554 /// CRYPTOPP_ENABLE_NAMESPACE_WEAK 1</tt> before including a header for a weak or wounded
555 /// algorithm. For example:
556 /// <pre>
557 /// \c \#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
558 /// \c \#include <md5.h>
559 /// ...
560 /// CryptoPP::Weak::MD5 md5;
561 /// </pre>
562 DOCUMENTED_NAMESPACE_BEGIN(Weak)
563 // weak and wounded algorithms
564 DOCUMENTED_NAMESPACE_END
565 #endif
566 
567 /// \brief Namespace containing NaCl library functions
568 /// \details TweetNaCl is a compact and portable reimplementation of the NaCl library.
569 DOCUMENTED_NAMESPACE_BEGIN(NaCl)
570 // crypto_box, crypto_box_open, crypto_sign, and crypto_sign_open (and friends)
571 DOCUMENTED_NAMESPACE_END
572 
573 /// \brief Namespace containing testing and benchmark classes.
574 /// \details Source files for classes in the Test namespaces include
575 /// <tt>test.cpp</tt>, <tt>validat#.cpp</tt> and <tt>bench#.cpp</tt>.
576 DOCUMENTED_NAMESPACE_BEGIN(Test)
577 // testing and benchmark classes
578 DOCUMENTED_NAMESPACE_END
579 
580 // ********************************************************
581 
582 /// \brief Interface for cloning objects
583 /// \note this is \a not implemented by most classes
584 /// \sa ClonableImpl, NotCopyable
585 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
586 {
587 public:
588  virtual ~Clonable() {}
589 
590  /// \brief Copies this object
591  /// \return a copy of this object
592  /// \throws NotImplemented
593  /// \note this is \a not implemented by most classes
594  /// \sa NotCopyable
595  virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
596 };
597 
598 /// \brief Interface for all crypto algorithms
599 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
600 {
601 public:
602  virtual ~Algorithm() {}
603 
604  /// \brief Interface for all crypto algorithms
605  /// \param checkSelfTestStatus determines whether the object can proceed if the self
606  /// tests have not been run or failed.
607  /// \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
608  /// this constructor throws SelfTestFailure if the self test hasn't been run or fails.
609  /// \details FIPS 140-2 compliance is disabled by default. It is only used by certain
610  /// versions of the library when the library is built as a DLL on Windows. Also see
611  /// CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h.
612  Algorithm(bool checkSelfTestStatus = true);
613 
614  /// \brief Provides the name of this algorithm
615  /// \return the standard algorithm name
616  /// \details The standard algorithm name can be a name like <tt>AES</tt> or <tt>AES/GCM</tt>.
617  /// Some algorithms do not have standard names yet. For example, there is no standard
618  /// algorithm name for Shoup's ECIES.
619  /// \note AlgorithmName is not universally implemented yet.
620  virtual std::string AlgorithmName() const {return "unknown";}
621 
622  /// \brief Retrieve the provider of this algorithm
623  /// \return the algorithm provider
624  /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
625  /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
626  /// usually indicate a specialized implementation using instructions from a higher
627  /// instruction set architecture (ISA). Future labels may include external hardware
628  /// like a hardware security module (HSM).
629  /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
630  /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
631  /// instead of ASM.
632  /// \details Algorithms which combine different instructions or ISAs provide the
633  /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
634  /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
635  /// \note Provider is not universally implemented yet.
636  /// \since Crypto++ 8.0
637  virtual std::string AlgorithmProvider() const {return "C++";}
638 };
639 
640 /// \brief Interface for algorithms that take byte strings as keys
641 /// \sa FixedKeyLength(), VariableKeyLength(), SameKeyLengthAs(), SimpleKeyingInterfaceImpl()
642 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
643 {
644 public:
645  virtual ~SimpleKeyingInterface() {}
646 
647  /// \brief Returns smallest valid key length
648  /// \returns the minimum key length, in bytes
649  virtual size_t MinKeyLength() const =0;
650 
651  /// \brief Returns largest valid key length
652  /// \returns the maximum key length, in bytes
653  virtual size_t MaxKeyLength() const =0;
654 
655  /// \brief Returns default key length
656  /// \returns the default key length, in bytes
657  virtual size_t DefaultKeyLength() const =0;
658 
659  /// \brief Returns a valid key length for the algorithm
660  /// \param keylength the size of the key, in bytes
661  /// \returns the valid key length, in bytes
662  /// \details keylength is provided in bytes, not bits. If keylength is less than MIN_KEYLENGTH,
663  /// then the function returns MIN_KEYLENGTH. If keylength is greater than MAX_KEYLENGTH,
664  /// then the function returns MAX_KEYLENGTH. if If keylength is a multiple of KEYLENGTH_MULTIPLE,
665  /// then keylength is returned. Otherwise, the function returns a \a lower multiple of
666  /// KEYLENGTH_MULTIPLE.
667  virtual size_t GetValidKeyLength(size_t keylength) const =0;
668 
669  /// \brief Returns whether keylength is a valid key length
670  /// \param keylength the requested keylength
671  /// \return true if keylength is valid, false otherwise
672  /// \details Internally the function calls GetValidKeyLength()
673  virtual bool IsValidKeyLength(size_t keylength) const
674  {return keylength == GetValidKeyLength(keylength);}
675 
676  /// \brief Sets or reset the key of this object
677  /// \param key the key to use when keying the object
678  /// \param length the size of the key, in bytes
679  /// \param params additional initialization parameters to configure this object
680  virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
681 
682  /// \brief Sets or reset the key of this object
683  /// \param key the key to use when keying the object
684  /// \param length the size of the key, in bytes
685  /// \param rounds the number of rounds to apply the transformation function,
686  /// if applicable
687  /// \details SetKeyWithRounds() calls SetKey() with a NameValuePairs
688  /// object that only specifies rounds. rounds is an integer parameter,
689  /// and <tt>-1</tt> means use the default number of rounds.
690  void SetKeyWithRounds(const byte *key, size_t length, int rounds);
691 
692  /// \brief Sets or reset the key of this object
693  /// \param key the key to use when keying the object
694  /// \param length the size of the key, in bytes
695  /// \param iv the initialization vector to use when keying the object
696  /// \param ivLength the size of the iv, in bytes
697  /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs
698  /// that only specifies IV. The IV is a byte buffer with size ivLength.
699  /// ivLength is an integer parameter, and <tt>-1</tt> means use IVSize().
700  void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
701 
702  /// \brief Sets or reset the key of this object
703  /// \param key the key to use when keying the object
704  /// \param length the size of the key, in bytes
705  /// \param iv the initialization vector to use when keying the object
706  /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs() object
707  /// that only specifies iv. iv is a byte buffer, and it must have
708  /// a size IVSize().
709  void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
710  {SetKeyWithIV(key, length, iv, IVSize());}
711 
712  /// \brief Secure IVs requirements as enumerated values.
713  /// \details Provides secure IV requirements as a monotonically increasing enumerated values.
714  /// Requirements can be compared using less than (&lt;) and greater than (&gt;). For example,
715  /// <tt>UNIQUE_IV &lt; RANDOM_IV</tt> and <tt>UNPREDICTABLE_RANDOM_IV &gt; RANDOM_IV</tt>.
716  /// \details Objects that use SimpleKeyingInterface do not support an optional IV. That is,
717  /// an IV must be present or it must be absent. If you wish to support an optional IV then
718  /// provide two classes - one with an IV and one without an IV.
719  /// \sa IsResynchronizable(), CanUseRandomIVs(), CanUsePredictableIVs(), CanUseStructuredIVs()
721  /// \brief The IV must be unique
722  UNIQUE_IV = 0,
723  /// \brief The IV must be random and possibly predictable
725  /// \brief The IV must be random and unpredictable
727  /// \brief The IV is set by the object
729  /// \brief The object does not use an IV
730  NOT_RESYNCHRONIZABLE
731  };
732 
733  /// \brief Minimal requirement for secure IVs
734  /// \return the secure IV requirement of the algorithm
735  virtual IV_Requirement IVRequirement() const =0;
736 
737  /// \brief Determines if the object can be resynchronized
738  /// \return true if the object can be resynchronized (i.e. supports initialization vectors), false otherwise
739  /// \note If this function returns true, and no IV is passed to SetKey() and <tt>CanUseStructuredIVs()==true</tt>,
740  /// an IV of all 0's will be assumed.
741  bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
742 
743  /// \brief Determines if the object can use random IVs
744  /// \return true if the object can use random IVs (in addition to ones returned by GetNextIV), false otherwise
745  bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
746 
747  /// \brief Determines if the object can use random but possibly predictable IVs
748  /// \return true if the object can use random but possibly predictable IVs (in addition to ones returned by
749  /// GetNextIV), false otherwise
750  bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
751 
752  /// \brief Determines if the object can use structured IVs
753  /// \returns true if the object can use structured IVs, false otherwise
754  /// \details CanUseStructuredIVs() indicates whether the object can use structured IVs; for example a counter
755  /// (in addition to ones returned by GetNextIV).
756  bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
757 
758  /// \brief Returns length of the IV accepted by this object
759  /// \return the size of an IV, in bytes
760  /// \throws NotImplemented() if the object does not support resynchronization
761  /// \details The default implementation throws NotImplemented
762  virtual unsigned int IVSize() const
763  {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
764 
765  /// \brief Provides the default size of an IV
766  /// \return default length of IVs accepted by this object, in bytes
767  unsigned int DefaultIVLength() const {return IVSize();}
768 
769  /// \brief Provides the minimum size of an IV
770  /// \return minimal length of IVs accepted by this object, in bytes
771  /// \throws NotImplemented() if the object does not support resynchronization
772  virtual unsigned int MinIVLength() const {return IVSize();}
773 
774  /// \brief Provides the maximum size of an IV
775  /// \return maximal length of IVs accepted by this object, in bytes
776  /// \throws NotImplemented() if the object does not support resynchronization
777  virtual unsigned int MaxIVLength() const {return IVSize();}
778 
779  /// \brief Resynchronize with an IV
780  /// \param iv the initialization vector
781  /// \param ivLength the size of the initialization vector, in bytes
782  /// \details Resynchronize() resynchronizes with an IV provided by the caller. <tt>ivLength=-1</tt> means use IVSize().
783  /// \throws NotImplemented() if the object does not support resynchronization
784  virtual void Resynchronize(const byte *iv, int ivLength=-1) {
785  CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength);
786  throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");
787  }
788 
789  /// \brief Retrieves a secure IV for the next message
790  /// \param rng a RandomNumberGenerator to produce keying material
791  /// \param iv a block of bytes to receive the IV
792  /// \details The IV must be at least IVSize() in length.
793  /// \details This method should be called after you finish encrypting one message and are ready
794  /// to start the next one. After calling it, you must call SetKey() or Resynchronize().
795  /// before using this object again.
796  /// \details Internally, the base class implementation calls RandomNumberGenerator's GenerateBlock()
797  /// \note This method is not implemented on decryption objects.
798  virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
799 
800 protected:
801  /// \brief Returns the base class Algorithm
802  /// \return the base class Algorithm
803  virtual const Algorithm & GetAlgorithm() const =0;
804 
805  /// \brief Sets the key for this object without performing parameter validation
806  /// \param key a byte buffer used to key the cipher
807  /// \param length the length of the byte buffer
808  /// \param params additional parameters passed as NameValuePairs
809  /// \details key must be at least DEFAULT_KEYLENGTH in length.
810  virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
811 
812  /// \brief Validates the key length
813  /// \param length the size of the keying material, in bytes
814  /// \throws InvalidKeyLength if the key length is invalid
815  void ThrowIfInvalidKeyLength(size_t length);
816 
817  /// \brief Validates the object
818  /// \throws InvalidArgument if the IV is present
819  /// \details Internally, the default implementation calls IsResynchronizable() and throws
820  /// InvalidArgument if the function returns true.
821  /// \note called when no IV is passed
822  void ThrowIfResynchronizable();
823 
824  /// \brief Validates the IV
825  /// \param iv the IV with a length of IVSize, in bytes
826  /// \throws InvalidArgument on failure
827  /// \details Internally, the default implementation checks the iv. If iv is not NULL or nullptr,
828  /// then the function succeeds. If iv is NULL, then IVRequirement is checked against
829  /// UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then
830  /// then the function succeeds. Otherwise, an exception is thrown.
831  void ThrowIfInvalidIV(const byte *iv);
832 
833  /// \brief Validates the IV length
834  /// \param length the size of an IV, in bytes
835  /// \throws InvalidArgument if the IV length is invalid
836  size_t ThrowIfInvalidIVLength(int length);
837 
838  /// \brief Retrieves and validates the IV
839  /// \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter
840  /// \param size the length of the IV, in bytes
841  /// \return a pointer to the first byte of the IV
842  /// \throws InvalidArgument if the number of rounds are invalid
843  const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
844 
845  /// \brief Validates the key length
846  /// \param length the size of the keying material, in bytes
847  inline void AssertValidKeyLength(size_t length) const
848  {CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));}
849 };
850 
851 /// \brief Interface for the data processing part of block ciphers
852 /// \details Classes derived from BlockTransformation are block ciphers
853 /// in ECB mode (for example the DES::Encryption class), which are stateless.
854 /// These classes should not be used directly, but only in combination with
855 /// a mode class (see CipherModeDocumentation in modes.h).
856 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
857 {
858 public:
859  virtual ~BlockTransformation() {}
860 
861  /// \brief Encrypt or decrypt a block
862  /// \param inBlock the input message before processing
863  /// \param outBlock the output message after processing
864  /// \param xorBlock an optional XOR mask
865  /// \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock.
866  /// \details The size of the block is determined by the block cipher and its documentation. Use
867  /// BLOCKSIZE at compile time, or BlockSize() at runtime.
868  /// \note The message can be transformed in-place, or the buffers must \a not overlap
869  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
870  virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
871 
872  /// \brief Encrypt or decrypt a block
873  /// \param inBlock the input message before processing
874  /// \param outBlock the output message after processing
875  /// \details ProcessBlock encrypts or decrypts inBlock and write to outBlock.
876  /// \details The size of the block is determined by the block cipher and its documentation.
877  /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
878  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
879  /// \note The message can be transformed in-place, or the buffers must \a not overlap
880  void ProcessBlock(const byte *inBlock, byte *outBlock) const
881  {ProcessAndXorBlock(inBlock, NULLPTR, outBlock);}
882 
883  /// \brief Encrypt or decrypt a block in place
884  /// \param inoutBlock the input message before processing
885  /// \details ProcessBlock encrypts or decrypts inoutBlock in-place.
886  /// \details The size of the block is determined by the block cipher and its documentation.
887  /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
888  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
889  void ProcessBlock(byte *inoutBlock) const
890  {ProcessAndXorBlock(inoutBlock, NULLPTR, inoutBlock);}
891 
892  /// Provides the block size of the cipher
893  /// \return the block size of the cipher, in bytes
894  virtual unsigned int BlockSize() const =0;
895 
896  /// \brief Provides input and output data alignment for optimal performance.
897  /// \return the input data alignment that provides optimal performance
898  /// \sa GetAlignment() and OptimalBlockSize()
899  virtual unsigned int OptimalDataAlignment() const;
900 
901  /// \brief Determines if the transformation is a permutation
902  /// \returns true if this is a permutation (i.e. there is an inverse transformation)
903  virtual bool IsPermutation() const {return true;}
904 
905  /// \brief Determines if the cipher is being operated in its forward direction
906  /// \returns true if DIR is ENCRYPTION, false otherwise
907  /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
908  virtual bool IsForwardTransformation() const =0;
909 
910  /// \brief Determines the number of blocks that can be processed in parallel
911  /// \return the number of blocks that can be processed in parallel, for bit-slicing implementations
912  /// \details Bit-slicing is often used to improve throughput and minimize timing attacks.
913  virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
914 
915  /// \brief Bit flags that control AdvancedProcessBlocks() behavior
917  /// \brief inBlock is a counter
918  BT_InBlockIsCounter=1,
919  /// \brief should not modify block pointers
920  BT_DontIncrementInOutPointers=2,
921  /// \brief Xor inputs before transformation
922  BT_XorInput=4,
923  /// \brief perform the transformation in reverse
924  BT_ReverseDirection=8,
925  /// \brief Allow parallel transformations
926  BT_AllowParallel=16};
927 
928  /// \brief Encrypt and xor multiple blocks using additional flags
929  /// \param inBlocks the input message before processing
930  /// \param xorBlocks an optional XOR mask
931  /// \param outBlocks the output message after processing
932  /// \param length the size of the blocks, in bytes
933  /// \param flags additional flags to control processing
934  /// \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags.
935  /// \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified.
936  virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
937 
938  /// \brief Provides the direction of the cipher
939  /// \return ENCRYPTION if IsForwardTransformation() is true, DECRYPTION otherwise
940  /// \sa IsForwardTransformation(), IsPermutation()
941  inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
942 };
943 
944 /// \brief Interface for the data processing portion of stream ciphers
945 /// \sa StreamTransformationFilter()
946 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
947 {
948 public:
949  virtual ~StreamTransformation() {}
950 
951  /// \brief Provides a reference to this object
952  /// \return A reference to this object
953  /// \details Useful for passing a temporary object to a function that takes a non-const reference
954  StreamTransformation& Ref() {return *this;}
955 
956  /// \brief Provides the mandatory block size of the cipher
957  /// \return The block size of the cipher if input must be processed in blocks, 1 otherwise
958  /// \details Stream ciphers and some block ciphers modes of operation return 1. Modes that
959  /// return 1 must be able to process a single byte at a time, like counter mode. If a
960  /// mode of operation or block cipher cannot stream then it must not return 1.
961  /// \details When filters operate the mode or cipher, ProcessData will be called with a
962  /// string of bytes that is determined by MandatoryBlockSize and OptimalBlockSize. When a
963  /// policy is set, like 16-byte strings for a 16-byte block cipher, the filter will buffer
964  /// bytes until the specified number of bytes is available to the object.
965  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
966  virtual unsigned int MandatoryBlockSize() const {return 1;}
967 
968  /// \brief Provides the input block size most efficient for this cipher
969  /// \return The input block size that is most efficient for the cipher
970  /// \details The base class implementation returns MandatoryBlockSize().
971  /// \note Optimal input length is
972  /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>.
973  virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
974 
975  /// \brief Provides the number of bytes used in the current block when processing at optimal block size.
976  /// \return the number of bytes used in the current block when processing at the optimal block size
977  virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
978 
979  /// \brief Provides input and output data alignment for optimal performance
980  /// \return the input data alignment that provides optimal performance
981  /// \sa GetAlignment() and OptimalBlockSize()
982  virtual unsigned int OptimalDataAlignment() const;
983 
984  /// \brief Encrypt or decrypt an array of bytes
985  /// \param outString the output byte buffer
986  /// \param inString the input byte buffer
987  /// \param length the size of the input and output byte buffers, in bytes
988  /// \details ProcessData is called with a string of bytes whose size depends on MandatoryBlockSize.
989  /// Either <tt>inString == outString</tt>, or they must not overlap.
990  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
991  virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
992 
993  /// \brief Encrypt or decrypt the last block of data
994  /// \param outString the output byte buffer
995  /// \param outLength the size of the output byte buffer, in bytes
996  /// \param inString the input byte buffer
997  /// \param inLength the size of the input byte buffer, in bytes
998  /// \returns the number of bytes used in outString
999  /// \details ProcessLastBlock is used when the last block of data is special and requires handling
1000  /// by the cipher. The current implementation provides an output buffer with a size
1001  /// <tt>inLength+2*MandatoryBlockSize()</tt>. The return value allows the cipher to expand cipher
1002  /// text during encryption or shrink plain text during decryption.
1003  /// \details This member function is used by CBC-CTS and OCB modes.
1004  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
1005  virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
1006 
1007  /// \brief Provides the size of the last block
1008  /// \returns the minimum size of the last block
1009  /// \details MinLastBlockSize() returns the minimum size of the last block. 0 indicates the last
1010  /// block is not special.
1011  /// \details MandatoryBlockSize() enlists one of two behaviors. First, if MandatoryBlockSize()
1012  /// returns 1, then the cipher can be streamed and ProcessData() is called with the tail bytes.
1013  /// Second, if MandatoryBlockSize() returns non-0, then the string of bytes is padded to
1014  /// MandatoryBlockSize() according to the padding mode. Then, ProcessData() is called with the
1015  /// padded string of bytes.
1016  /// \details Some authenticated encryption modes are not expressed well with MandatoryBlockSize()
1017  /// and MinLastBlockSize(). For example, AES/OCB uses 16-byte blocks (MandatoryBlockSize = 16)
1018  /// and the last block requires special processing (MinLastBlockSize = 0). However, 0 is a valid
1019  /// last block size for OCB and the special processing is custom padding, and not standard PKCS
1020  /// padding. In response an unambiguous IsLastBlockSpecial() was added.
1021  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
1022  virtual unsigned int MinLastBlockSize() const {return 0;}
1023 
1024  /// \brief Determines if the last block receives special processing
1025  /// \returns true if the last block reveives special processing, false otherwise.
1026  /// \details Some authenticated encryption modes are not expressed well with
1027  /// MandatoryBlockSize() and MinLastBlockSize(). For example, AES/OCB uses
1028  /// 16-byte blocks (MandatoryBlockSize = 16) and the last block requires special processing
1029  /// (MinLastBlockSize = 0). However, 0 is a valid last block size for OCB and the special
1030  /// processing is custom padding, and not standard PKCS padding. In response an
1031  /// unambiguous IsLastBlockSpecial() was added.
1032  /// \details When IsLastBlockSpecial() returns false nothing special happens. All the former
1033  /// rules and behaviors apply. This is the default behavior of IsLastBlockSpecial().
1034  /// \details When IsLastBlockSpecial() returns true four things happen. First, MinLastBlockSize = 0
1035  /// means 0 is a valid block size that should be processed. Second, standard block cipher padding is
1036  /// \a not \a applied. Third, the caller supplies an outString is larger than inString by
1037  /// <tt>2*MandatoryBlockSize()</tt>. That is, there's a reserve available when processing the last block.
1038  /// Fourth, the cipher is responsible for finalization like custom padding. The cipher will tell
1039  /// the library how many bytes were processed or used by returning the appropriate value from
1040  /// ProcessLastBlock().
1041  /// \details The return value of ProcessLastBlock() indicates how many bytes were written to
1042  /// <tt>outString</tt>. A filter pipelining data will send <tt>outString</tt> and up to <tt>outLength</tt>
1043  /// to an <tt>AttachedTransformation()</tt> for additional processing. Below is an example of the code
1044  /// used in <tt>StreamTransformationFilter::LastPut</tt>.
1045  /// <pre> if (m_cipher.IsLastBlockSpecial())
1046  /// {
1047  /// size_t reserve = 2*m_cipher.MandatoryBlockSize();
1048  /// space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, length+reserve);
1049  /// length = m_cipher.ProcessLastBlock(space, length+reserve, inString, length);
1050  /// AttachedTransformation()->Put(space, length);
1051  /// return;
1052  /// }</pre>
1053  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
1054  /// \since Crypto++ 6.0
1055  virtual bool IsLastBlockSpecial() const {return false;}
1056 
1057  /// \brief Encrypt or decrypt a string of bytes
1058  /// \param inoutString the string to process
1059  /// \param length the size of the inoutString, in bytes
1060  /// \details Internally, the base class implementation calls ProcessData().
1061  inline void ProcessString(byte *inoutString, size_t length)
1062  {ProcessData(inoutString, inoutString, length);}
1063 
1064  /// \brief Encrypt or decrypt a string of bytes
1065  /// \param outString the output string to process
1066  /// \param inString the input string to process
1067  /// \param length the size of the input and output strings, in bytes
1068  /// \details Internally, the base class implementation calls ProcessData().
1069  inline void ProcessString(byte *outString, const byte *inString, size_t length)
1070  {ProcessData(outString, inString, length);}
1071 
1072  /// \brief Encrypt or decrypt a byte
1073  /// \param input the input byte to process
1074  /// \details Internally, the base class implementation calls ProcessData() with a size of 1.
1075  inline byte ProcessByte(byte input)
1076  {ProcessData(&input, &input, 1); return input;}
1077 
1078  /// \brief Determines whether the cipher supports random access
1079  /// \returns true if the cipher supports random access, false otherwise
1080  virtual bool IsRandomAccess() const =0;
1081 
1082  /// \brief Seek to an absolute position
1083  /// \param pos position to seek
1084  /// \throws NotImplemented
1085  /// \details The base class implementation throws NotImplemented. The function
1086  /// \ref CRYPTOPP_ASSERT "asserts" IsRandomAccess() in debug builds.
1087  virtual void Seek(lword pos)
1088  {
1089  CRYPTOPP_UNUSED(pos);
1090  CRYPTOPP_ASSERT(!IsRandomAccess());
1091  throw NotImplemented("StreamTransformation: this object doesn't support random access");
1092  }
1093 
1094  /// \brief Determines whether the cipher is self-inverting
1095  /// \returns true if the cipher is self-inverting, false otherwise
1096  /// \details IsSelfInverting determines whether this transformation is
1097  /// self-inverting (e.g. xor with a keystream).
1098  virtual bool IsSelfInverting() const =0;
1099 
1100  /// \brief Determines if the cipher is being operated in its forward direction
1101  /// \returns true if DIR is ENCRYPTION, false otherwise
1102  /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
1103  virtual bool IsForwardTransformation() const =0;
1104 };
1105 
1106 /// \brief Interface for hash functions and data processing part of MACs
1107 /// \details HashTransformation objects are stateful. They are created in an initial state,
1108 /// change state as Update() is called, and return to the initial
1109 /// state when Final() is called. This interface allows a large message to
1110 /// be hashed in pieces by calling Update() on each piece followed by
1111 /// calling Final().
1112 /// \sa HashFilter(), HashVerificationFilter()
1113 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
1114 {
1115 public:
1116  virtual ~HashTransformation() {}
1117 
1118  /// \brief Provides a reference to this object
1119  /// \return A reference to this object
1120  /// \details Useful for passing a temporary object to a function that takes a non-const reference
1121  HashTransformation& Ref() {return *this;}
1122 
1123  /// \brief Updates a hash with additional input
1124  /// \param input the additional input as a buffer
1125  /// \param length the size of the buffer, in bytes
1126  virtual void Update(const byte *input, size_t length) =0;
1127 
1128  /// \brief Request space which can be written into by the caller
1129  /// \param size the requested size of the buffer
1130  /// \details The purpose of this method is to help avoid extra memory allocations.
1131  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1132  /// size is the requested size of the buffer. When the call returns, size is the size of
1133  /// the array returned to the caller.
1134  /// \details The base class implementation sets size to 0 and returns NULL or nullptr.
1135  /// \note Some objects, like ArraySink, cannot create a space because its fixed.
1136  virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULLPTR;}
1137 
1138  /// \brief Computes the hash of the current message
1139  /// \param digest a pointer to the buffer to receive the hash
1140  /// \details Final() restarts the hash for a new message.
1141  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1142  /// the output byte buffer is large enough for the digest.
1143  virtual void Final(byte *digest)
1144  {TruncatedFinal(digest, DigestSize());}
1145 
1146  /// \brief Restart the hash
1147  /// \details Discards the current state, and restart for a new message
1148  virtual void Restart()
1149  {TruncatedFinal(NULLPTR, 0);}
1150 
1151  /// Provides the digest size of the hash
1152  /// \return the digest size of the hash.
1153  virtual unsigned int DigestSize() const =0;
1154 
1155  /// Provides the tag size of the hash
1156  /// \return the tag size of the hash.
1157  /// \details Same as DigestSize().
1158  unsigned int TagSize() const {return DigestSize();}
1159 
1160  /// \brief Provides the block size of the compression function
1161  /// \return block size of the compression function, in bytes
1162  /// \details BlockSize() will return 0 if the hash is not block based
1163  /// or does not have an equivalent block size. For example, Keccak
1164  /// and SHA-3 do not have a block size, but they do have an equivalent
1165  /// block size called rate expressed as <tt>r</tt>.
1166  virtual unsigned int BlockSize() const {return 0;}
1167 
1168  /// \brief Provides the input block size most efficient for this hash.
1169  /// \return The input block size that is most efficient for the cipher
1170  /// \details The base class implementation returns MandatoryBlockSize().
1171  /// \details Optimal input length is
1172  /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>.
1173  virtual unsigned int OptimalBlockSize() const {return 1;}
1174 
1175  /// \brief Provides input and output data alignment for optimal performance
1176  /// \return the input data alignment that provides optimal performance
1177  /// \sa GetAlignment() and OptimalBlockSize()
1178  virtual unsigned int OptimalDataAlignment() const;
1179 
1180  /// \brief Updates the hash with additional input and computes the hash of the current message
1181  /// \param digest a pointer to the buffer to receive the hash
1182  /// \param input the additional input as a buffer
1183  /// \param length the size of the buffer, in bytes
1184  /// \details Use this if your input is in one piece and you don't want to call Update()
1185  /// and Final() separately
1186  /// \details CalculateDigest() restarts the hash for the next message.
1187  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1188  /// the output byte buffer is large enough for the digest.
1189  virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
1190  {Update(input, length); Final(digest);}
1191 
1192  /// \brief Verifies the hash of the current message
1193  /// \param digest a pointer to the buffer of an \a existing hash
1194  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1195  /// \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
1196  /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
1197  /// a constant time comparison function. digestLength cannot exceed DigestSize().
1198  /// \details Verify() restarts the hash for the next message.
1199  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1200  /// the output byte buffer is large enough for the digest.
1201  virtual bool Verify(const byte *digest)
1202  {return TruncatedVerify(digest, DigestSize());}
1203 
1204  /// \brief Updates the hash with additional input and verifies the hash of the current message
1205  /// \param digest a pointer to the buffer of an \a existing hash
1206  /// \param input the additional input as a buffer
1207  /// \param length the size of the buffer, in bytes
1208  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1209  /// \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
1210  /// \details Use this if your input is in one piece and you don't want to call Update()
1211  /// and Verify() separately
1212  /// \details VerifyDigest() performs a bitwise compare on the buffers using VerifyBufsEqual(),
1213  /// which is a constant time comparison function. digestLength cannot exceed DigestSize().
1214  /// \details VerifyDigest() restarts the hash for the next message.
1215  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1216  /// the output byte buffer is large enough for the digest.
1217  virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
1218  {Update(input, length); return Verify(digest);}
1219 
1220  /// \brief Computes the hash of the current message
1221  /// \param digest a pointer to the buffer to receive the hash
1222  /// \param digestSize the size of the truncated digest, in bytes
1223  /// \details TruncatedFinal() call Final() and then copies digestSize bytes to digest.
1224  /// The hash is restarted the hash for the next message.
1225  virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
1226 
1227  /// \brief Updates the hash with additional input and computes the hash of the current message
1228  /// \param digest a pointer to the buffer to receive the hash
1229  /// \param digestSize the length of the truncated hash, in bytes
1230  /// \param input the additional input as a buffer
1231  /// \param length the size of the buffer, in bytes
1232  /// \details Use this if your input is in one piece and you don't want to call Update()
1233  /// and CalculateDigest() separately.
1234  /// \details CalculateTruncatedDigest() restarts the hash for the next message.
1235  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1236  /// the output byte buffer is large enough for the digest.
1237  virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
1238  {Update(input, length); TruncatedFinal(digest, digestSize);}
1239 
1240  /// \brief Verifies the hash of the current message
1241  /// \param digest a pointer to the buffer of an \a existing hash
1242  /// \param digestLength the size of the truncated hash, in bytes
1243  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1244  /// \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
1245  /// \details TruncatedVerify() is a truncated version of Verify(). It can operate on a
1246  /// buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
1247  /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
1248  /// a constant time comparison function. digestLength cannot exceed DigestSize().
1249  /// \details TruncatedVerify() restarts the hash for the next message.
1250  virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
1251 
1252  /// \brief Updates the hash with additional input and verifies the hash of the current message
1253  /// \param digest a pointer to the buffer of an \a existing hash
1254  /// \param digestLength the size of the truncated hash, in bytes
1255  /// \param input the additional input as a buffer
1256  /// \param length the size of the buffer, in bytes
1257  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1258  /// \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
1259  /// \details Use this if your input is in one piece and you don't want to call Update()
1260  /// and TruncatedVerify() separately.
1261  /// \details VerifyTruncatedDigest() is a truncated version of VerifyDigest(). It can operate
1262  /// on a buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
1263  /// \details VerifyTruncatedDigest() restarts the hash for the next message.
1264  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1265  /// the output byte buffer is large enough for the digest.
1266  virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
1267  {Update(input, length); return TruncatedVerify(digest, digestLength);}
1268 
1269 protected:
1270  /// \brief Validates a truncated digest size
1271  /// \param size the requested digest size
1272  /// \throws InvalidArgument if the algorithm's digest size cannot be truncated to the requested size
1273  /// \details Throws an exception when the truncated digest size is greater than DigestSize()
1274  void ThrowIfInvalidTruncatedSize(size_t size) const;
1275 };
1276 
1277 /// \brief Interface for one direction (encryption or decryption) of a block cipher
1278 /// \details These objects usually should not be used directly. See BlockTransformation for more details.
1279 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
1280 {
1281 protected:
1282  const Algorithm & GetAlgorithm() const {return *this;}
1283 };
1284 
1285 /// \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode
1286 /// \details These objects usually should not be used directly. See StreamTransformation for more details.
1287 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
1288 {
1289 protected:
1290  const Algorithm & GetAlgorithm() const {return *this;}
1291 };
1292 
1293 /// \brief Interface for message authentication codes
1294 /// \details These objects usually should not be used directly. See HashTransformation for more details.
1295 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
1296 {
1297 protected:
1298  const Algorithm & GetAlgorithm() const {return *this;}
1299 };
1300 
1301 /// \brief Interface for authenticated encryption modes of operation
1302 /// \details AuthenticatedSymmetricCipher() provides the interface for one direction
1303 /// (encryption or decryption) of a stream cipher or block cipher mode with authentication. The
1304 /// StreamTransformation() part of this interface is used to encrypt or decrypt the data. The
1305 /// MessageAuthenticationCode() part of the interface is used to input additional authenticated
1306 /// data (AAD), which is MAC'ed but not encrypted. The MessageAuthenticationCode() part is also
1307 /// used to generate and verify the MAC.
1308 /// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
1309 /// and OCB mode. All modes implement AuthenticatedSymmetricCipher() and the motivation for
1310 /// the API, like calling AAD a &quot;header&quot;, can be found in Bellare, Rogaway and
1311 /// Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX Mode of
1312 /// Operation</A>. The EAX paper suggested a basic API to help standardize AEAD schemes in
1313 /// software and promote adoption of the modes.
1314 /// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
1315 /// Encryption</A> on the Crypto++ wiki.
1316 /// \since Crypto++ 5.6.0
1317 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
1318 {
1319 public:
1320  virtual ~AuthenticatedSymmetricCipher() {}
1321 
1322  /// \brief Exception thrown when the object is in the wrong state for the operation
1323  /// \details this indicates that a member function was called in the wrong state, for example trying to encrypt
1324  /// a message before having set the key or IV
1325  class BadState : public Exception
1326  {
1327  public:
1328  explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
1329  explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
1330  };
1331 
1332  /// \brief Provides the maximum length of AAD that can be input
1333  /// \return the maximum length of AAD that can be input before the encrypted data
1334  virtual lword MaxHeaderLength() const =0;
1335 
1336  /// \brief Provides the maximum length of encrypted data
1337  /// \return the maximum length of encrypted data
1338  virtual lword MaxMessageLength() const =0;
1339 
1340  /// \brief Provides the the maximum length of AAD
1341  /// \return the maximum length of AAD that can be input after the encrypted data
1342  virtual lword MaxFooterLength() const {return 0;}
1343 
1344  /// \brief Determines if data lengths must be specified prior to inputting data
1345  /// \return true if the data lengths are required before inputting data, false otherwise
1346  /// \details if this function returns true, SpecifyDataLengths() must be called before attempting to input data.
1347  /// This is the case for some schemes, such as CCM.
1348  /// \sa SpecifyDataLengths()
1349  virtual bool NeedsPrespecifiedDataLengths() const {return false;}
1350 
1351  /// \brief Prescribes the data lengths
1352  /// \param headerLength size of data before message is input, in bytes
1353  /// \param messageLength size of the message, in bytes
1354  /// \param footerLength size of data after message is input, in bytes
1355  /// \details SpecifyDataLengths() only needs to be called if NeedsPrespecifiedDataLengths() returns <tt>true</tt>.
1356  /// If <tt>true</tt>, then <tt>headerLength</tt> will be validated against <tt>MaxHeaderLength()</tt>,
1357  /// <tt>messageLength</tt> will be validated against <tt>MaxMessageLength()</tt>, and
1358  /// <tt>footerLength</tt> will be validated against <tt>MaxFooterLength()</tt>.
1359  /// \sa NeedsPrespecifiedDataLengths()
1360  void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
1361 
1362  /// \brief Encrypts and calculates a MAC in one call
1363  /// \param ciphertext the encryption buffer
1364  /// \param mac the mac buffer
1365  /// \param macSize the size of the MAC buffer, in bytes
1366  /// \param iv the iv buffer
1367  /// \param ivLength the size of the IV buffer, in bytes
1368  /// \param header the AAD buffer
1369  /// \param headerLength the size of the AAD buffer, in bytes
1370  /// \param message the message buffer
1371  /// \param messageLength the size of the messagetext buffer, in bytes
1372  /// \details EncryptAndAuthenticate() encrypts and generates the MAC in one call. The function
1373  /// truncates the MAC if <tt>macSize < TagSize()</tt>.
1374  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);
1375 
1376  /// \brief Decrypts and verifies a MAC in one call
1377  /// \param message the decryption buffer
1378  /// \param mac the mac buffer
1379  /// \param macSize the size of the MAC buffer, in bytes
1380  /// \param iv the iv buffer
1381  /// \param ivLength the size of the IV buffer, in bytes
1382  /// \param header the AAD buffer
1383  /// \param headerLength the size of the AAD buffer, in bytes
1384  /// \param ciphertext the ciphertext buffer
1385  /// \param ciphertextLength the size of the ciphertext buffer, in bytes
1386  /// \return true if the MAC is valid and the decoding succeeded, false otherwise
1387  /// \details DecryptAndVerify() decrypts and verifies the MAC in one call.
1388  /// <tt>message</tt> is a decryption buffer and should be at least as large as the ciphertext buffer.
1389  /// \details The function returns true iff MAC is valid. DecryptAndVerify() assumes the MAC
1390  /// is truncated if <tt>macLength < TagSize()</tt>.
1391  virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength);
1392 
1393  /// \brief Provides the name of this algorithm
1394  /// \return the standard algorithm name
1395  /// \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms
1396  /// do not have standard names yet. For example, there is no standard algorithm name for
1397  /// Shoup's ECIES.
1398  virtual std::string AlgorithmName() const;
1399 
1400 protected:
1401  const Algorithm & GetAlgorithm() const
1402  {return *static_cast<const MessageAuthenticationCode *>(this);}
1403  virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
1404  {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);}
1405 };
1406 
1407 /// \brief Interface for random number generators
1408 /// \details The library provides a number of random number generators, from software based
1409 /// to hardware based generators.
1410 /// \details All generated values are uniformly distributed over the range specified.
1411 /// \since Crypto++ 3.1
1412 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
1413 {
1414 public:
1415  virtual ~RandomNumberGenerator() {}
1416 
1417  /// \brief Update RNG state with additional unpredictable values
1418  /// \param input the entropy to add to the generator
1419  /// \param length the size of the input buffer
1420  /// \throws NotImplemented
1421  /// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy()
1422  /// to test for the ability to use additional entropy.
1423  /// \details If a derived class does not override IncorporateEntropy(), then the base class
1424  /// throws NotImplemented.
1425  virtual void IncorporateEntropy(const byte *input, size_t length)
1426  {
1427  CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
1428  throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
1429  }
1430 
1431  /// \brief Determines if a generator can accept additional entropy
1432  /// \return true if IncorporateEntropy() is implemented
1433  virtual bool CanIncorporateEntropy() const {return false;}
1434 
1435  /// \brief Generate new random byte and return it
1436  /// \return a random 8-bit byte
1437  /// \details Default implementation calls GenerateBlock() with one byte.
1438  /// \details All generated values are uniformly distributed over the range specified within the
1439  /// the constraints of a particular generator.
1440  virtual byte GenerateByte();
1441 
1442  /// \brief Generate new random bit and return it
1443  /// \return a random bit
1444  /// \details The default implementation calls GenerateByte() and return its lowest bit.
1445  /// \details All generated values are uniformly distributed over the range specified within the
1446  /// the constraints of a particular generator.
1447  virtual unsigned int GenerateBit();
1448 
1449  /// \brief Generate a random 32 bit word in the range min to max, inclusive
1450  /// \param min the lower bound of the range
1451  /// \param max the upper bound of the range
1452  /// \return a random 32-bit word
1453  /// \details The default implementation calls Crop() on the difference between max and
1454  /// min, and then returns the result added to min.
1455  /// \details All generated values are uniformly distributed over the range specified within the
1456  /// the constraints of a particular generator.
1457  virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL);
1458 
1459  /// \brief Generate random array of bytes
1460  /// \param output the byte buffer
1461  /// \param size the length of the buffer, in bytes
1462  /// \details All generated values are uniformly distributed over the range specified within the
1463  /// the constraints of a particular generator.
1464  /// \note A derived generator \a must override either GenerateBlock() or
1465  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1466  virtual void GenerateBlock(byte *output, size_t size);
1467 
1468  /// \brief Generate random bytes into a BufferedTransformation
1469  /// \param target the BufferedTransformation object which receives the bytes
1470  /// \param channel the channel on which the bytes should be pumped
1471  /// \param length the number of bytes to generate
1472  /// \details The default implementation calls GenerateBlock() and pumps the result into
1473  /// the DEFAULT_CHANNEL of the target.
1474  /// \details All generated values are uniformly distributed over the range specified within the
1475  /// the constraints of a particular generator.
1476  /// \note A derived generator \a must override either GenerateBlock() or
1477  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1478  virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
1479 
1480  /// \brief Generate and discard n bytes
1481  /// \param n the number of bytes to generate and discard
1482  virtual void DiscardBytes(size_t n);
1483 
1484  /// \brief Randomly shuffle the specified array
1485  /// \param begin an iterator to the first element in the array
1486  /// \param end an iterator beyond the last element in the array
1487  /// \details The resulting permutation is uniformly distributed.
1488  template <class IT> void Shuffle(IT begin, IT end)
1489  {
1490  // TODO: What happens if there are more than 2^32 elements?
1491  for (; begin != end; ++begin)
1492  std::iter_swap(begin, begin + GenerateWord32(0, static_cast<word32>(end-begin-1)));
1493  }
1494 };
1495 
1496 /// \brief Interface for key derivation functions
1497 /// \since Crypto++ 7.0
1498 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm
1499 {
1500 public:
1501  virtual ~KeyDerivationFunction() {}
1502 
1503  /// \brief Provides the name of this algorithm
1504  /// \return the standard algorithm name
1505  virtual std::string AlgorithmName() const =0;
1506 
1507  /// \brief Determine minimum number of bytes
1508  /// \returns Minimum number of bytes which can be derived
1509  virtual size_t MinDerivedKeyLength() const;
1510 
1511  /// \brief Determine maximum number of bytes
1512  /// \returns Maximum number of bytes which can be derived
1513  virtual size_t MaxDerivedKeyLength() const;
1514 
1515  /// \brief Returns a valid key length for the derivation function
1516  /// \param keylength the size of the derived key, in bytes
1517  /// \returns the valid key length, in bytes
1518  virtual size_t GetValidDerivedLength(size_t keylength) const =0;
1519 
1520  /// \brief Returns whether keylength is a valid key length
1521  /// \param keylength the requested keylength
1522  /// \return true if the derived keylength is valid, false otherwise
1523  /// \details Internally the function calls GetValidKeyLength()
1524  virtual bool IsValidDerivedLength(size_t keylength) const {
1525  return keylength == GetValidDerivedLength(keylength);
1526  }
1527 
1528  /// \brief Derive a key from a seed
1529  /// \param derived the derived output buffer
1530  /// \param derivedLen the size of the derived buffer, in bytes
1531  /// \param secret the seed input buffer
1532  /// \param secretLen the size of the secret buffer, in bytes
1533  /// \param params additional initialization parameters to configure this object
1534  /// \returns the number of iterations performed
1535  /// \throws InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme
1536  /// \details DeriveKey() provides a standard interface to derive a key from
1537  /// a secret seed and other parameters. Each class that derives from KeyDerivationFunction
1538  /// provides an overload that accepts most parameters used by the derivation function.
1539  /// \details the number of iterations performed by DeriveKey() may be 1. For example, a
1540  /// scheme like HKDF does not use the iteration count so it returns 1.
1541  virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params = g_nullNameValuePairs) const =0;
1542 
1543  /// \brief Set or change parameters
1544  /// \param params additional initialization parameters to configure this object
1545  /// \details SetParameters() is useful for setting common parameters when an object is
1546  /// reused. Some derivation function classes may choose to implement it.
1547  virtual void SetParameters(const NameValuePairs& params);
1548 
1549 protected:
1550  /// \brief Returns the base class Algorithm
1551  /// \return the base class Algorithm
1552  virtual const Algorithm & GetAlgorithm() const =0;
1553 
1554  /// \brief Validates the derived key length
1555  /// \param length the size of the derived key material, in bytes
1556  /// \throws InvalidKeyLength if the key length is invalid
1557  void ThrowIfInvalidDerivedKeyLength(size_t length) const;
1558 };
1559 
1560 /// \brief Interface for password based key derivation functions
1561 /// \since Crypto++ 7.0
1563 {
1564 };
1565 
1566 /// \brief Random Number Generator that does not produce random numbers
1567 /// \return reference that can be passed to functions that require a RandomNumberGenerator
1568 /// \details NullRNG() returns a reference that can be passed to functions that require a
1569 /// RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented
1570 /// when a generation function is called.
1571 /// \sa ClassNullRNG, PK_SignatureScheme::IsProbabilistic()
1572 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
1573 
1574 class WaitObjectContainer;
1575 class CallStack;
1576 
1577 /// \brief Interface for objects that can be waited on.
1578 class CRYPTOPP_NO_VTABLE Waitable
1579 {
1580 public:
1581  virtual ~Waitable() {}
1582 
1583  /// \brief Maximum number of wait objects that this object can return
1584  /// \return the maximum number of wait objects
1585  virtual unsigned int GetMaxWaitObjectCount() const =0;
1586 
1587  /// \brief Retrieves waitable objects
1588  /// \param container the wait container to receive the references to the objects.
1589  /// \param callStack CallStack() object used to select waitable objects
1590  /// \details GetWaitObjects() is usually called in one of two ways. First, it can
1591  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1592  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1593  /// parameter, it can be called like
1594  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1595  virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
1596 
1597  /// \brief Wait on this object
1598  /// \return true if the wait succeeded, false otherwise
1599  /// \details Wait() is the same as creating an empty container, calling GetWaitObjects(), and then calling
1600  /// Wait() on the container.
1601  bool Wait(unsigned long milliseconds, CallStack const& callStack);
1602 };
1603 
1604 /// \brief Interface for buffered transformations
1605 /// \details BufferedTransformation is a generalization of BlockTransformation,
1606 /// StreamTransformation and HashTransformation.
1607 /// \details A buffered transformation is an object that takes a stream of bytes as input (this may
1608 /// be done in stages), does some computation on them, and then places the result into an internal
1609 /// buffer for later retrieval. Any partial result already in the output buffer is not modified
1610 /// by further input.
1611 /// \details If a method takes a "blocking" parameter, and you pass false for it, then the method
1612 /// will return before all input has been processed if the input cannot be processed without waiting
1613 /// (for network buffers to become available, for example). In this case the method will return true
1614 /// or a non-zero integer value. When this happens you must continue to call the method with the same
1615 /// parameters until it returns false or zero, before calling any other method on it or attached
1616 /// /p BufferedTransformation. The integer return value in this case is approximately
1617 /// the number of bytes left to be processed, and can be used to implement a progress bar.
1618 /// \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on
1619 /// the signal to attached BufferedTransformation objects, with propagation decremented at each
1620 /// step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation.
1621 /// \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual
1622 /// number of bytes retrieved, which is the lesser of the request number and MaxRetrievable().
1623 /// \details \a Most of the input functions, like Put() and PutWord32(), return the number of
1624 /// bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value
1625 /// means bytes remain to be processed.
1626 /// \nosubgrouping
1627 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
1628 {
1629 public:
1630  virtual ~BufferedTransformation() {}
1631 
1632  /// \brief Construct a BufferedTransformation
1634 
1635  /// \brief Provides a reference to this object
1636  /// \return A reference to this object
1637  /// \details Useful for passing a temporary object to a function that takes a non-const reference
1638  BufferedTransformation& Ref() {return *this;}
1639 
1640  /// \name INPUT
1641  //@{
1642 
1643  /// \brief Input a byte for processing
1644  /// \param inByte the 8-bit byte (octet) to be processed.
1645  /// \param blocking specifies whether the object should block when processing input.
1646  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1647  /// 0 indicates all bytes were processed.
1648  /// \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>.
1649  size_t Put(byte inByte, bool blocking=true)
1650  {return Put(&inByte, 1, blocking);}
1651 
1652  /// \brief Input a byte buffer for processing
1653  /// \param inString the byte buffer to process
1654  /// \param length the size of the string, in bytes
1655  /// \param blocking specifies whether the object should block when processing input
1656  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1657  /// 0 indicates all bytes were processed.
1658  /// \details Internally, Put() calls Put2().
1659  size_t Put(const byte *inString, size_t length, bool blocking=true)
1660  {return Put2(inString, length, 0, blocking);}
1661 
1662  /// Input a 16-bit word for processing.
1663  /// \param value the 16-bit value to be processed
1664  /// \param order the ByteOrder of the value to be processed.
1665  /// \param blocking specifies whether the object should block when processing input
1666  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1667  /// 0 indicates all bytes were processed.
1668  size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1669 
1670  /// Input a 32-bit word for processing.
1671  /// \param value the 32-bit value to be processed.
1672  /// \param order the ByteOrder of the value to be processed.
1673  /// \param blocking specifies whether the object should block when processing input.
1674  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1675  /// 0 indicates all bytes were processed.
1676  size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1677 
1678  /// Input a 64-bit word for processing.
1679  /// \param value the 64-bit value to be processed.
1680  /// \param order the ByteOrder of the value to be processed.
1681  /// \param blocking specifies whether the object should block when processing input.
1682  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1683  /// 0 indicates all bytes were processed.
1684  size_t PutWord64(word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1685 
1686  /// \brief Request space which can be written into by the caller
1687  /// \param size the requested size of the buffer
1688  /// \return byte pointer to the space to input data
1689  /// \details The purpose of this method is to help avoid extra memory allocations.
1690  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1691  /// size is the requested size of the buffer. When the call returns, size is the size of
1692  /// the array returned to the caller.
1693  /// \details The base class implementation sets size to 0 and returns NULL.
1694  /// \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
1695  /// an ArraySink, the pointer to the array is returned and the size is remaining size.
1696  virtual byte * CreatePutSpace(size_t &size)
1697  {size=0; return NULLPTR;}
1698 
1699  /// \brief Determines whether input can be modified by the callee
1700  /// \return true if input can be modified, false otherwise
1701  /// \details The base class implementation returns false.
1702  virtual bool CanModifyInput() const
1703  {return false;}
1704 
1705  /// \brief Input multiple bytes that may be modified by callee.
1706  /// \param inString the byte buffer to process
1707  /// \param length the size of the string, in bytes
1708  /// \param blocking specifies whether the object should block when processing input
1709  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1710  /// bytes were processed.
1711  size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
1712  {return PutModifiable2(inString, length, 0, blocking);}
1713 
1714  /// \brief Signals the end of messages to the object
1715  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1716  /// \param blocking specifies whether the object should block when processing input
1717  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1718  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1719  bool MessageEnd(int propagation=-1, bool blocking=true)
1720  {return !!Put2(NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
1721 
1722  /// \brief Input multiple bytes for processing and signal the end of a message
1723  /// \param inString the byte buffer to process
1724  /// \param length the size of the string, in bytes
1725  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1726  /// \param blocking specifies whether the object should block when processing input
1727  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1728  /// bytes were processed.
1729  /// \details Internally, PutMessageEnd() calls Put2() with a modified propagation to
1730  /// ensure all attached transformations finish processing the message.
1731  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1732  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1733  size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
1734  {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
1735 
1736  /// \brief Input multiple bytes for processing
1737  /// \param inString the byte buffer to process
1738  /// \param length the size of the string, in bytes
1739  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
1740  /// \param blocking specifies whether the object should block when processing input
1741  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1742  /// bytes were processed.
1743  /// \details Derived classes must implement Put2().
1744  virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
1745 
1746  /// \brief Input multiple bytes that may be modified by callee.
1747  /// \param inString the byte buffer to process.
1748  /// \param length the size of the string, in bytes.
1749  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
1750  /// \param blocking specifies whether the object should block when processing input.
1751  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1752  /// bytes were processed.
1753  /// \details Internally, PutModifiable2() calls Put2().
1754  virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
1755  {return Put2(inString, length, messageEnd, blocking);}
1756 
1757  /// \brief Exception thrown by objects that have \a not implemented nonblocking input processing
1758  /// \details BlockingInputOnly inherits from NotImplemented
1760  {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
1761  //@}
1762 
1763  /// \name WAITING
1764  //@{
1765  /// \brief Retrieves the maximum number of waitable objects
1766  unsigned int GetMaxWaitObjectCount() const;
1767 
1768  /// \brief Retrieves waitable objects
1769  /// \param container the wait container to receive the references to the objects
1770  /// \param callStack CallStack() object used to select waitable objects
1771  /// \details GetWaitObjects is usually called in one of two ways. First, it can
1772  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1773  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1774  /// parameter, it can be called like
1775  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1776  void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
1777  //@} // WAITING
1778 
1779  /// \name SIGNALS
1780  //@{
1781 
1782  /// \brief Initialize or reinitialize this object, without signal propagation
1783  /// \param parameters a set of NameValuePairs to initialize this object
1784  /// \throws NotImplemented
1785  /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
1786  /// number of arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1787  /// all possible combintations of configurable parameters.
1788  /// \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization
1789  /// should be propagated, then use the Initialize() function.
1790  /// \details If a derived class does not override IsolatedInitialize(), then the base class throws
1791  /// NotImplemented.
1792  virtual void IsolatedInitialize(const NameValuePairs &parameters) {
1793  CRYPTOPP_UNUSED(parameters);
1794  throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
1795  }
1796 
1797  /// \brief Flushes data buffered by this object, without signal propagation
1798  /// \param hardFlush indicates whether all data should be flushed
1799  /// \param blocking specifies whether the object should block when processing input
1800  /// \note hardFlush must be used with care
1801  virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
1802 
1803  /// \brief Marks the end of a series of messages, without signal propagation
1804  /// \param blocking specifies whether the object should block when completing the processing on
1805  /// the current series of messages
1806  virtual bool IsolatedMessageSeriesEnd(bool blocking)
1807  {CRYPTOPP_UNUSED(blocking); return false;}
1808 
1809  /// \brief Initialize or reinitialize this object, with signal propagation
1810  /// \param parameters a set of NameValuePairs to initialize or reinitialize this object
1811  /// \param propagation the number of attached transformations the Initialize() signal should be passed
1812  /// \details Initialize() is used to initialize or reinitialize an object using a variable number of
1813  /// arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1814  /// all possible combintations of configurable parameters.
1815  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1816  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1817  virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
1818 
1819  /// \brief Flush buffered input and/or output, with signal propagation
1820  /// \param hardFlush is used to indicate whether all data should be flushed
1821  /// \param propagation the number of attached transformations the Flush()
1822  /// signal should be passed
1823  /// \param blocking specifies whether the object should block when processing
1824  /// input
1825  /// \details propagation count includes this object. Setting propagation to
1826  /// <tt>1</tt> means this object only. Setting propagation to <tt>-1</tt>
1827  /// means unlimited propagation.
1828  /// \note Hard flushes must be used with care. It means try to process and
1829  /// output everything, even if there may not be enough data to complete the
1830  /// action. For example, hard flushing a HexDecoder would cause an error if
1831  /// you do it after inputing an odd number of hex encoded characters.
1832  /// \note For some types of filters, like ZlibDecompressor, hard flushes can
1833  /// only be done at "synchronization points". These synchronization points
1834  /// are positions in the data stream that are created by hard flushes on the
1835  /// corresponding reverse filters, in this example ZlibCompressor. This is
1836  /// useful when zlib compressed data is moved across a network in packets
1837  /// and compression state is preserved across packets, as in the SSH2 protocol.
1838  virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
1839 
1840  /// \brief Marks the end of a series of messages, with signal propagation
1841  /// \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
1842  /// \param blocking specifies whether the object should block when processing input
1843  /// \details Each object that receives the signal will perform its processing, decrement
1844  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
1845  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1846  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1847  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
1848  virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
1849 
1850  /// \brief Set propagation of automatically generated and transferred signals
1851  /// \param propagation then new value
1852  /// \details Setting propagation to <tt>0</tt> means do not automatically generate signals. Setting
1853  /// propagation to <tt>-1</tt> means unlimited propagation.
1854  virtual void SetAutoSignalPropagation(int propagation)
1855  {CRYPTOPP_UNUSED(propagation);}
1856 
1857  /// \brief Retrieve automatic signal propagation value
1858  /// \return the number of attached transformations the signal is propagated to. 0 indicates
1859  /// the signal is only witnessed by this object
1860  virtual int GetAutoSignalPropagation() const {return 0;}
1861 public:
1862 
1863  /// \name RETRIEVAL OF ONE MESSAGE
1864  //@{
1865 
1866  /// \brief Provides the number of bytes ready for retrieval
1867  /// \return the number of bytes ready for retrieval
1868  /// \details All retrieval functions return the actual number of bytes retrieved, which is
1869  /// the lesser of the request number and MaxRetrievable()
1870  virtual lword MaxRetrievable() const;
1871 
1872  /// \brief Determines whether bytes are ready for retrieval
1873  /// \returns true if bytes are available for retrieval, false otherwise
1874  virtual bool AnyRetrievable() const;
1875 
1876  /// \brief Retrieve a 8-bit byte
1877  /// \param outByte the 8-bit value to be retrieved
1878  /// \return the number of bytes consumed during the call.
1879  /// \details Use the return value of Get to detect short reads.
1880  virtual size_t Get(byte &outByte);
1881 
1882  /// \brief Retrieve a block of bytes
1883  /// \param outString a block of bytes
1884  /// \param getMax the number of bytes to Get
1885  /// \return the number of bytes consumed during the call.
1886  /// \details Use the return value of Get to detect short reads.
1887  virtual size_t Get(byte *outString, size_t getMax);
1888 
1889  /// \brief Peek a 8-bit byte
1890  /// \param outByte the 8-bit value to be retrieved
1891  /// \return the number of bytes read during the call.
1892  /// \details Peek does not remove bytes from the object. Use the return value of
1893  /// Get() to detect short reads.
1894  virtual size_t Peek(byte &outByte) const;
1895 
1896  /// \brief Peek a block of bytes
1897  /// \param outString a block of bytes
1898  /// \param peekMax the number of bytes to Peek
1899  /// \return the number of bytes read during the call.
1900  /// \details Peek does not remove bytes from the object. Use the return value of
1901  /// Peek() to detect short reads.
1902  virtual size_t Peek(byte *outString, size_t peekMax) const;
1903 
1904  /// \brief Retrieve a 16-bit word
1905  /// \param value the 16-bit value to be retrieved
1906  /// \param order the ByteOrder of the value to be processed.
1907  /// \return the number of bytes consumed during the call.
1908  /// \details Use the return value of GetWord16() to detect short reads.
1909  size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1910 
1911  /// \brief Retrieve a 32-bit word
1912  /// \param value the 32-bit value to be retrieved
1913  /// \param order the ByteOrder of the value to be processed.
1914  /// \return the number of bytes consumed during the call.
1915  /// \details Use the return value of GetWord32() to detect short reads.
1916  size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1917 
1918  /// \brief Retrieve a 64-bit word
1919  /// \param value the 64-bit value to be retrieved
1920  /// \param order the ByteOrder of the value to be processed.
1921  /// \return the number of bytes consumed during the call.
1922  /// \details Use the return value of GetWord64() to detect short reads.
1923  /// \since Crypto++ 8.3
1924  size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1925 
1926  /// \brief Peek a 16-bit word
1927  /// \param value the 16-bit value to be retrieved
1928  /// \param order the ByteOrder of the value to be processed.
1929  /// \return the number of bytes consumed during the call.
1930  /// \details Peek does not consume bytes in the stream. Use the return value
1931  /// of PeekWord16() to detect short reads.
1932  size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1933 
1934  /// \brief Peek a 32-bit word
1935  /// \param value the 32-bit value to be retrieved
1936  /// \param order the ByteOrder of the value to be processed.
1937  /// \return the number of bytes consumed during the call.
1938  /// \details Peek does not consume bytes in the stream. Use the return value
1939  /// of PeekWord32() to detect short reads.
1940  size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1941 
1942  /// \brief Peek a 64-bit word
1943  /// \param value the 64-bit value to be retrieved
1944  /// \param order the ByteOrder of the value to be processed.
1945  /// \return the number of bytes consumed during the call.
1946  /// \details Peek does not consume bytes in the stream. Use the return value
1947  /// of PeekWord64() to detect short reads.
1948  /// \since Crypto++ 8.3
1949  size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1950 
1951  /// move transferMax bytes of the buffered output to target as input
1952 
1953  /// \brief Transfer bytes from this object to another BufferedTransformation
1954  /// \param target the destination BufferedTransformation
1955  /// \param transferMax the number of bytes to transfer
1956  /// \param channel the channel on which the transfer should occur
1957  /// \return the number of bytes transferred during the call.
1958  /// \details TransferTo removes bytes from this object and moves them to the destination.
1959  /// \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2().
1960  lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
1961  {TransferTo2(target, transferMax, channel); return transferMax;}
1962 
1963  /// \brief Discard skipMax bytes from the output buffer
1964  /// \param skipMax the number of bytes to discard
1965  /// \details Skip() discards bytes from the output buffer, which is the AttachedTransformation(), if present.
1966  /// The function always returns the parameter <tt>skipMax</tt>.
1967  /// \details If you want to skip bytes from a Source, then perform the following.
1968  /// <pre>
1969  /// StringSource ss(str, false, new Redirector(TheBitBucket()));
1970  /// ss.Pump(10); // Skip 10 bytes from Source
1971  /// ss.Detach(new FilterChain(...));
1972  /// ss.PumpAll();
1973  /// </pre>
1974  virtual lword Skip(lword skipMax=LWORD_MAX);
1975 
1976  /// copy copyMax bytes of the buffered output to target as input
1977 
1978  /// \brief Copy bytes from this object to another BufferedTransformation
1979  /// \param target the destination BufferedTransformation
1980  /// \param copyMax the number of bytes to copy
1981  /// \param channel the channel on which the transfer should occur
1982  /// \return the number of bytes copied during the call.
1983  /// \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
1984  /// \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2().
1985  lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1986  {return CopyRangeTo(target, 0, copyMax, channel);}
1987 
1988  /// \brief Copy bytes from this object using an index to another BufferedTransformation
1989  /// \param target the destination BufferedTransformation
1990  /// \param position the 0-based index of the byte stream to begin the copying
1991  /// \param copyMax the number of bytes to copy
1992  /// \param channel the channel on which the transfer should occur
1993  /// \return the number of bytes copied during the call.
1994  /// \details CopyTo copies bytes from this object to the destination. The bytes remain in this
1995  /// object. Copying begins at the index position in the current stream, and not from an absolute
1996  /// position in the stream.
1997  /// \details The function returns the new position in the stream after transferring the bytes starting at the index.
1998  lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1999  {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
2000  //@}
2001 
2002  /// \name RETRIEVAL OF MULTIPLE MESSAGES
2003  //@{
2004 
2005  /// \brief Provides the number of bytes ready for retrieval
2006  /// \return the number of bytes ready for retrieval
2007  virtual lword TotalBytesRetrievable() const;
2008 
2009  /// \brief Provides the number of meesages processed by this object
2010  /// \return the number of meesages processed by this object
2011  /// \details NumberOfMessages returns number of times MessageEnd() has been
2012  /// received minus messages retrieved or skipped
2013  virtual unsigned int NumberOfMessages() const;
2014 
2015  /// \brief Determines if any messages are available for retrieval
2016  /// \returns true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
2017  /// \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
2018  virtual bool AnyMessages() const;
2019 
2020  /// \brief Start retrieving the next message
2021  /// \return true if a message is ready for retrieval
2022  /// \details GetNextMessage() returns true if a message is ready for retrieval; false
2023  /// if no more messages exist or this message is not completely retrieved.
2024  virtual bool GetNextMessage();
2025 
2026  /// \brief Skip a number of meessages
2027  /// \return 0 if the requested number of messages was skipped, non-0 otherwise
2028  /// \details SkipMessages() skips count number of messages. If there is an AttachedTransformation()
2029  /// then SkipMessages() is called on the attached transformation. If there is no attached
2030  /// transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo().
2031  virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
2032 
2033  /// \brief Transfer messages from this object to another BufferedTransformation
2034  /// \param target the destination BufferedTransformation
2035  /// \param count the number of messages to transfer
2036  /// \param channel the channel on which the transfer should occur
2037  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2038  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2039  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
2040  /// bytes is returned. TransferMessagesTo() does not proceed to the next message.
2041  /// \details A return value of 0 indicates all messages were successfully transferred.
2042  unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
2043  {TransferMessagesTo2(target, count, channel); return count;}
2044 
2045  /// \brief Copy messages from this object to another BufferedTransformation
2046  /// \param target the destination BufferedTransformation
2047  /// \param count the number of messages to transfer
2048  /// \param channel the channel on which the transfer should occur
2049  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2050  /// \details CopyMessagesTo copies messages from this object and copies them to the destination.
2051  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
2052  /// bytes is returned. CopyMessagesTo() does not proceed to the next message.
2053  /// \details A return value of 0 indicates all messages were successfully copied.
2054  unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
2055 
2056  /// \brief Skip all messages in the series
2057  virtual void SkipAll();
2058 
2059  /// \brief Transfer all bytes from this object to another BufferedTransformation
2060  /// \param target the destination BufferedTransformation
2061  /// \param channel the channel on which the transfer should occur
2062  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2063  /// Internally TransferAllTo() calls TransferAllTo2().
2064  void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
2065  {TransferAllTo2(target, channel);}
2066 
2067  /// \brief Copy messages from this object to another BufferedTransformation
2068  /// \param target the destination BufferedTransformation
2069  /// \param channel the channel on which the transfer should occur
2070  /// \details CopyAllTo copies messages from this object and copies them to the destination.
2071  void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
2072 
2073  /// \brief Retrieve the next message in a series
2074  /// \return true if a message was retreved, false otherwise
2075  /// \details Internally, the base class implementation returns false.
2076  virtual bool GetNextMessageSeries() {return false;}
2077  /// \brief Provides the number of messages in a series
2078  /// \return the number of messages in this series
2079  virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
2080  /// \brief Provides the number of messages in a series
2081  /// \return the number of messages in this series
2082  virtual unsigned int NumberOfMessageSeries() const {return 0;}
2083  //@}
2084 
2085  /// \name NON-BLOCKING TRANSFER OF OUTPUT
2086  //@{
2087 
2088  // upon return, byteCount contains number of bytes that have finished being transferred,
2089  // and returns the number of bytes left in the current transfer block
2090 
2091  /// \brief Transfer bytes from this object to another BufferedTransformation
2092  /// \param target the destination BufferedTransformation
2093  /// \param byteCount the number of bytes to transfer
2094  /// \param channel the channel on which the transfer should occur
2095  /// \param blocking specifies whether the object should block when processing input
2096  /// \return the number of bytes that remain in the transfer block (i.e., bytes not transferred)
2097  /// \details TransferTo2() removes bytes from this object and moves them to the destination.
2098  /// Transfer begins at the index position in the current stream, and not from an absolute
2099  /// position in the stream.
2100  /// \details byteCount is an \a IN and \a OUT parameter. When the call is made,
2101  /// byteCount is the requested size of the transfer. When the call returns, byteCount is
2102  /// the number of bytes that were transferred.
2103  virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
2104 
2105  // upon return, begin contains the start position of data yet to be finished copying,
2106  // and returns the number of bytes left in the current transfer block
2107 
2108  /// \brief Copy bytes from this object to another BufferedTransformation
2109  /// \param target the destination BufferedTransformation
2110  /// \param begin the 0-based index of the first byte to copy in the stream
2111  /// \param end the 0-based index of the last byte to copy in the stream
2112  /// \param channel the channel on which the transfer should occur
2113  /// \param blocking specifies whether the object should block when processing input
2114  /// \return the number of bytes that remain in the copy block (i.e., bytes not copied)
2115  /// \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not
2116  /// removed from this object. Copying begins at the index position in the current stream, and
2117  /// not from an absolute position in the stream.
2118  /// \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the
2119  /// starting position of the copy. When the call returns, begin is the position of the first
2120  /// byte that was \a not copied (which may be different than end). begin can be used for
2121  /// subsequent calls to CopyRangeTo2().
2122  virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
2123 
2124  // upon return, messageCount contains number of messages that have finished being transferred,
2125  // and returns the number of bytes left in the current transfer block
2126 
2127  /// \brief Transfer messages from this object to another BufferedTransformation
2128  /// \param target the destination BufferedTransformation
2129  /// \param messageCount the number of messages to transfer
2130  /// \param channel the channel on which the transfer should occur
2131  /// \param blocking specifies whether the object should block when processing input
2132  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2133  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2134  /// \details messageCount is an \a IN and \a OUT parameter. When the call is made, messageCount is the
2135  /// the number of messages requested to be transferred. When the call returns, messageCount is the
2136  /// number of messages actually transferred.
2137  size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2138 
2139  // returns the number of bytes left in the current transfer block
2140 
2141  /// \brief Transfer all bytes from this object to another BufferedTransformation
2142  /// \param target the destination BufferedTransformation
2143  /// \param channel the channel on which the transfer should occur
2144  /// \param blocking specifies whether the object should block when processing input
2145  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2146  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2147  size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2148  //@}
2149 
2150  /// \name CHANNELS
2151  //@{
2152  /// \brief Exception thrown when a filter does not support named channels
2154  {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
2155  /// \brief Exception thrown when a filter does not recognize a named channel
2157  {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
2158 
2159  /// \brief Input a byte for processing on a channel
2160  /// \param channel the channel to process the data.
2161  /// \param inByte the 8-bit byte (octet) to be processed.
2162  /// \param blocking specifies whether the object should block when processing input.
2163  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2164  /// number of bytes that were not processed.
2165  size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
2166  {return ChannelPut(channel, &inByte, 1, blocking);}
2167 
2168  /// \brief Input a byte buffer for processing on a channel
2169  /// \param channel the channel to process the data
2170  /// \param inString the byte buffer to process
2171  /// \param length the size of the string, in bytes
2172  /// \param blocking specifies whether the object should block when processing input
2173  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2174  /// number of bytes that were not processed.
2175  size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
2176  {return ChannelPut2(channel, inString, length, 0, blocking);}
2177 
2178  /// \brief Input multiple bytes that may be modified by callee on a channel
2179  /// \param channel the channel to process the data.
2180  /// \param inString the byte buffer to process
2181  /// \param length the size of the string, in bytes
2182  /// \param blocking specifies whether the object should block when processing input
2183  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2184  /// number of bytes that were not processed.
2185  size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
2186  {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
2187 
2188  /// \brief Input a 16-bit word for processing on a channel.
2189  /// \param channel the channel to process the data.
2190  /// \param value the 16-bit value to be processed.
2191  /// \param order the ByteOrder of the value to be processed.
2192  /// \param blocking specifies whether the object should block when processing input.
2193  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2194  /// number of bytes that were not processed.
2195  size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2196 
2197  /// \brief Input a 32-bit word for processing on a channel.
2198  /// \param channel the channel to process the data.
2199  /// \param value the 32-bit value to be processed.
2200  /// \param order the ByteOrder of the value to be processed.
2201  /// \param blocking specifies whether the object should block when processing input.
2202  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2203  /// number of bytes that were not processed.
2204  size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2205 
2206  /// \brief Input a 64-bit word for processing on a channel.
2207  /// \param channel the channel to process the data.
2208  /// \param value the 64-bit value to be processed.
2209  /// \param order the ByteOrder of the value to be processed.
2210  /// \param blocking specifies whether the object should block when processing input.
2211  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2212  /// number of bytes that were not processed.
2213  size_t ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2214 
2215  /// \brief Signal the end of a message
2216  /// \param channel the channel to process the data.
2217  /// \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed
2218  /// \param blocking specifies whether the object should block when processing input
2219  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2220  /// number of bytes that were not processed.
2221  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2222  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2223  bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
2224  {return !!ChannelPut2(channel, NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
2225 
2226  /// \brief Input multiple bytes for processing and signal the end of a message
2227  /// \param channel the channel to process the data.
2228  /// \param inString the byte buffer to process
2229  /// \param length the size of the string, in bytes
2230  /// \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed
2231  /// \param blocking specifies whether the object should block when processing input
2232  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2233  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2234  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2235  size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
2236  {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
2237 
2238  /// \brief Request space which can be written into by the caller
2239  /// \param channel the channel to process the data
2240  /// \param size the requested size of the buffer
2241  /// \return a pointer to a memory block with length size
2242  /// \details The purpose of this method is to help avoid extra memory allocations.
2243  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
2244  /// size is the requested size of the buffer. When the call returns, size is the size of
2245  /// the array returned to the caller.
2246  /// \details The base class implementation sets size to 0 and returns NULL.
2247  /// \note Some objects, like ArraySink(), cannot create a space because its fixed. In the case of
2248  /// an ArraySink(), the pointer to the array is returned and the size is remaining size.
2249  virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
2250 
2251  /// \brief Input multiple bytes for processing on a channel.
2252  /// \param channel the channel to process the data.
2253  /// \param inString the byte buffer to process.
2254  /// \param length the size of the string, in bytes.
2255  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
2256  /// \param blocking specifies whether the object should block when processing input.
2257  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2258  virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
2259 
2260  /// \brief Input multiple bytes that may be modified by callee on a channel
2261  /// \param channel the channel to process the data
2262  /// \param inString the byte buffer to process
2263  /// \param length the size of the string, in bytes
2264  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
2265  /// \param blocking specifies whether the object should block when processing input
2266  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2267  virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
2268 
2269  /// \brief Flush buffered input and/or output on a channel
2270  /// \param channel the channel to flush the data
2271  /// \param hardFlush is used to indicate whether all data should be flushed
2272  /// \param propagation the number of attached transformations the ChannelFlush() signal should be passed
2273  /// \param blocking specifies whether the object should block when processing input
2274  /// \return true of the Flush was successful
2275  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2276  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2277  virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
2278 
2279  /// \brief Marks the end of a series of messages on a channel
2280  /// \param channel the channel to signal the end of a series of messages
2281  /// \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed
2282  /// \param blocking specifies whether the object should block when processing input
2283  /// \details Each object that receives the signal will perform its processing, decrement
2284  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
2285  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2286  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2287  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
2288  virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
2289 
2290  /// \brief Sets the default retrieval channel
2291  /// \param channel the channel to signal the end of a series of messages
2292  /// \note this function may not be implemented in all objects that should support it.
2293  virtual void SetRetrievalChannel(const std::string &channel);
2294  //@}
2295 
2296  /// \name ATTACHMENT
2297  /// \details Some BufferedTransformation objects (e.g. Filter objects) allow other BufferedTransformation objects to be
2298  /// attached. When this is done, the first object instead of buffering its output, sends that output to the attached
2299  /// object as input. The entire attachment chain is deleted when the anchor object is destructed.
2300 
2301  //@{
2302  /// \brief Determines whether the object allows attachment
2303  /// \return true if the object allows an attachment, false otherwise
2304  /// \details Sources and Filters will returns true, while Sinks and other objects will return false.
2305  virtual bool Attachable() {return false;}
2306 
2307  /// \brief Returns the object immediately attached to this object
2308  /// \return the attached transformation
2309  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2310  /// version of AttachedTransformation() always returns NULL.
2311  virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;}
2312 
2313  /// \brief Returns the object immediately attached to this object
2314  /// \return the attached transformation
2315  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2316  /// version of AttachedTransformation() always returns NULL.
2318  {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
2319 
2320  /// \brief Delete the current attachment chain and attach a new one
2321  /// \param newAttachment the new BufferedTransformation to attach
2322  /// \throws NotImplemented
2323  /// \details Detach() deletes the current attachment chain and replace it with an optional newAttachment
2324  /// \details If a derived class does not override Detach(), then the base class throws
2325  /// NotImplemented.
2326  virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) {
2327  CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable());
2328  throw NotImplemented("BufferedTransformation: this object is not attachable");
2329  }
2330 
2331  /// \brief Add newAttachment to the end of attachment chain
2332  /// \param newAttachment the attachment to add to the end of the chain
2333  virtual void Attach(BufferedTransformation *newAttachment);
2334  //@}
2335 
2336 protected:
2337  /// \brief Decrements the propagation count while clamping at 0
2338  /// \return the decremented propagation or 0
2339  static int DecrementPropagation(int propagation)
2340  {return propagation != 0 ? propagation - 1 : 0;}
2341 
2342 private:
2343  // for ChannelPutWord16, ChannelPutWord32 and ChannelPutWord64,
2344  // to ensure the buffer isn't deallocated before non-blocking
2345  // operation completes
2346  byte m_buf[8];
2347 };
2348 
2349 /// \brief An input discarding BufferedTransformation
2350 /// \return a reference to a BufferedTransformation object that discards all input
2351 CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
2352 
2353 /// \brief Interface for crypto material, such as public and private keys, and crypto parameters
2354 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
2355 {
2356 public:
2357  /// Exception thrown when invalid crypto material is detected
2358  class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
2359  {
2360  public:
2361  explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
2362  };
2363 
2364  virtual ~CryptoMaterial() {}
2365 
2366  /// \brief Assign values to this object
2367  /// \details This function can be used to create a public key from a private key.
2368  virtual void AssignFrom(const NameValuePairs &source) =0;
2369 
2370  /// \brief Check this object for errors
2371  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2372  /// \param level the level of thoroughness
2373  /// \returns true if the tests succeed, false otherwise
2374  /// \details There are four levels of thoroughness:
2375  /// <ul>
2376  /// <li>0 - using this object won't cause a crash or exception
2377  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
2378  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
2379  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
2380  /// </ul>
2381  /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
2382  /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
2383  /// \sa ThrowIfInvalid()
2384  virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
2385 
2386  /// \brief Check this object for errors
2387  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2388  /// \param level the level of thoroughness
2389  /// \throws InvalidMaterial
2390  /// \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial() if validation fails.
2391  /// \sa Validate()
2392  virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
2393  {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
2394 
2395  /// \brief Saves a key to a BufferedTransformation
2396  /// \param bt the destination BufferedTransformation
2397  /// \throws NotImplemented
2398  /// \details Save() writes the material to a BufferedTransformation.
2399  /// \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
2400  /// includes an object identifier with an algorthm id, like a subjectPublicKeyInfo.
2401  /// \details A "raw" key without the "key info" can be saved using a key's DEREncode() method.
2402  /// \details If a derived class does not override Save(), then the base class throws
2403  /// NotImplemented().
2404  virtual void Save(BufferedTransformation &bt) const
2405  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
2406 
2407  /// \brief Loads a key from a BufferedTransformation
2408  /// \param bt the source BufferedTransformation
2409  /// \throws KeyingErr
2410  /// \details Load() attempts to read material from a BufferedTransformation. If the
2411  /// material is a key that was generated outside the library, then the following
2412  /// usually applies:
2413  /// <ul>
2414  /// <li>the key should be ASN.1 BER encoded
2415  /// <li>the key should be a "key info"
2416  /// </ul>
2417  /// \details "key info" means the key should have an object identifier with an algorthm id,
2418  /// like a subjectPublicKeyInfo.
2419  /// \details To read a "raw" key without the "key info", then call the key's BERDecode() method.
2420  /// \note Load() generally does not check that the key is valid. Call Validate(), if needed.
2421  virtual void Load(BufferedTransformation &bt)
2422  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
2423 
2424  /// \brief Determines whether the object supports precomputation
2425  /// \return true if the object supports precomputation, false otherwise
2426  /// \sa Precompute()
2427  virtual bool SupportsPrecomputation() const {return false;}
2428 
2429  /// \brief Perform precomputation
2430  /// \param precomputationStorage the suggested number of objects for the precompute table
2431  /// \throws NotImplemented
2432  /// \details The exact semantics of Precompute() varies, but it typically means calculate
2433  /// a table of n objects that can be used later to speed up computation.
2434  /// \details If a derived class does not override Precompute(), then the base class throws
2435  /// NotImplemented.
2436  /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation()
2437  virtual void Precompute(unsigned int precomputationStorage) {
2438  CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation());
2439  throw NotImplemented("CryptoMaterial: this object does not support precomputation");
2440  }
2441 
2442  /// \brief Retrieve previously saved precomputation
2443  /// \param storedPrecomputation BufferedTransformation with the saved precomputation
2444  /// \throws NotImplemented
2445  /// \sa SupportsPrecomputation(), Precompute()
2446  virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
2447  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2448 
2449  /// \brief Save precomputation for later use
2450  /// \param storedPrecomputation BufferedTransformation to write the precomputation
2451  /// \throws NotImplemented
2452  /// \sa SupportsPrecomputation(), Precompute()
2453  virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
2454  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2455 
2456  /// \brief Perform a quick sanity check
2457  /// \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users.
2458  void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
2459 
2460 #if defined(__SUNPRO_CC)
2461  // Sun Studio 11/CC 5.8 workaround: it generates incorrect code
2462  // when casting to an empty virtual base class. JW, 2018: It is
2463  // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable
2464  // it everywhere in case it affects SPARC (which we don't test).
2465  char m_sunCCworkaround;
2466 #endif
2467 };
2468 
2469 /// \brief Interface for generatable crypto material, such as private keys and crypto parameters
2470 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
2471 {
2472 public:
2473  virtual ~GeneratableCryptoMaterial() {}
2474 
2475  /// \brief Generate a random key or crypto parameters
2476  /// \param rng a RandomNumberGenerator to produce keying material
2477  /// \param params additional initialization parameters
2478  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2479  /// \details If a derived class does not override GenerateRandom(), then the base class throws
2480  /// NotImplemented.
2482  CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
2483  throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
2484  }
2485 
2486  /// \brief Generate a random key or crypto parameters
2487  /// \param rng a RandomNumberGenerator to produce keying material
2488  /// \param keySize the size of the key, in bits
2489  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2490  /// \details GenerateRandomWithKeySize calls GenerateRandom() with a NameValuePairs
2491  /// object with only "KeySize"
2492  void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
2493 };
2494 
2495 /// \brief Interface for public keys
2496 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
2497 {
2498 };
2499 
2500 /// \brief Interface for private keys
2501 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
2502 {
2503 };
2504 
2505 /// \brief Interface for crypto prameters
2506 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
2507 {
2508 };
2509 
2510 /// \brief Interface for asymmetric algorithms
2511 /// \details BERDecode() and DEREncode() were removed under Issue 569
2512 /// and Commit 9b174e84de7a. Programs should use <tt>AccessMaterial().Load(bt)</tt>
2513 /// or <tt>AccessMaterial().Save(bt)</tt> instead.
2514 /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/569">Issue 569</A>
2515 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
2516 {
2517 public:
2518  virtual ~AsymmetricAlgorithm() {}
2519 
2520  /// \brief Retrieves a reference to CryptoMaterial
2521  /// \return a reference to the crypto material
2522  virtual CryptoMaterial & AccessMaterial() =0;
2523 
2524  /// \brief Retrieves a reference to CryptoMaterial
2525  /// \return a const reference to the crypto material
2526  virtual const CryptoMaterial & GetMaterial() const =0;
2527 
2528 #if 0
2529  /// \brief Loads this object from a BufferedTransformation
2530  /// \param bt a BufferedTransformation object
2531  /// \details Use of BERDecode() changed to Load() at Issue 569.
2532  /// \deprecated for backwards compatibility, calls <tt>AccessMaterial().Load(bt)</tt>
2533  void BERDecode(BufferedTransformation &bt)
2534  {AccessMaterial().Load(bt);}
2535 
2536  /// \brief Saves this object to a BufferedTransformation
2537  /// \param bt a BufferedTransformation object
2538  /// \details Use of DEREncode() changed to Save() at Issue 569.
2539  /// \deprecated for backwards compatibility, calls GetMaterial().Save(bt)
2540  void DEREncode(BufferedTransformation &bt) const
2541  {GetMaterial().Save(bt);}
2542 #endif
2543 };
2544 
2545 /// \brief Interface for asymmetric algorithms using public keys
2546 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
2547 {
2548 public:
2549  virtual ~PublicKeyAlgorithm() {}
2550 
2551  // VC60 workaround: no co-variant return type
2552 
2553  /// \brief Retrieves a reference to a Public Key
2554  /// \return a reference to the public key
2556  {return AccessPublicKey();}
2557  /// \brief Retrieves a reference to a Public Key
2558  /// \return a const reference the public key
2559  const CryptoMaterial & GetMaterial() const
2560  {return GetPublicKey();}
2561 
2562  /// \brief Retrieves a reference to a Public Key
2563  /// \return a reference to the public key
2564  virtual PublicKey & AccessPublicKey() =0;
2565  /// \brief Retrieves a reference to a Public Key
2566  /// \return a const reference the public key
2567  virtual const PublicKey & GetPublicKey() const
2568  {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
2569 };
2570 
2571 /// \brief Interface for asymmetric algorithms using private keys
2572 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
2573 {
2574 public:
2575  virtual ~PrivateKeyAlgorithm() {}
2576 
2577  /// \brief Retrieves a reference to a Private Key
2578  /// \return a reference the private key
2579  CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
2580  /// \brief Retrieves a reference to a Private Key
2581  /// \return a const reference the private key
2582  const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
2583 
2584  /// \brief Retrieves a reference to a Private Key
2585  /// \return a reference the private key
2586  virtual PrivateKey & AccessPrivateKey() =0;
2587  /// \brief Retrieves a reference to a Private Key
2588  /// \return a const reference the private key
2589  virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
2590 };
2591 
2592 /// \brief Interface for key agreement algorithms
2593 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
2594 {
2595 public:
2596  virtual ~KeyAgreementAlgorithm() {}
2597 
2598  /// \brief Retrieves a reference to Crypto Parameters
2599  /// \return a reference the crypto parameters
2600  CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
2601  /// \brief Retrieves a reference to Crypto Parameters
2602  /// \return a const reference the crypto parameters
2603  const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
2604 
2605  /// \brief Retrieves a reference to Crypto Parameters
2606  /// \return a reference the crypto parameters
2607  virtual CryptoParameters & AccessCryptoParameters() =0;
2608  /// \brief Retrieves a reference to Crypto Parameters
2609  /// \return a const reference the crypto parameters
2610  virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
2611 };
2612 
2613 /// \brief Interface for public-key encryptors and decryptors
2614 /// \details This class provides an interface common to encryptors and decryptors
2615 /// for querying their plaintext and ciphertext lengths.
2616 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
2617 {
2618 public:
2619  virtual ~PK_CryptoSystem() {}
2620 
2621  /// \brief Provides the maximum length of plaintext for a given ciphertext length
2622  /// \return the maximum size of the plaintext, in bytes
2623  /// \details This function returns 0 if ciphertextLength is not valid (too long or too short).
2624  virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
2625 
2626  /// \brief Calculate the length of ciphertext given length of plaintext
2627  /// \return the maximum size of the ciphertext, in bytes
2628  /// \details This function returns 0 if plaintextLength is not valid (too long).
2629  virtual size_t CiphertextLength(size_t plaintextLength) const =0;
2630 
2631  /// \brief Determines whether this object supports the use of a named parameter
2632  /// \param name the name of the parameter
2633  /// \return true if the parameter name is supported, false otherwise
2634  /// \details Some possible parameter names: EncodingParameters(), KeyDerivationParameters()
2635  /// and others Parameters listed in argnames.h
2636  virtual bool ParameterSupported(const char *name) const =0;
2637 
2638  /// \brief Provides the fixed ciphertext length, if one exists
2639  /// \return the fixed ciphertext length if one exists, otherwise 0
2640  /// \details "Fixed" here means length of ciphertext does not depend on length of plaintext.
2641  /// In this case, it usually does depend on the key length.
2642  virtual size_t FixedCiphertextLength() const {return 0;}
2643 
2644  /// \brief Provides the maximum plaintext length given a fixed ciphertext length
2645  /// \return maximum plaintext length given the fixed ciphertext length, if one exists,
2646  /// otherwise return 0.
2647  /// \details FixedMaxPlaintextLength(0 returns the maximum plaintext length given the fixed ciphertext
2648  /// length, if one exists, otherwise return 0.
2649  virtual size_t FixedMaxPlaintextLength() const {return 0;}
2650 };
2651 
2652 /// \brief Interface for public-key encryptors
2653 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
2654 {
2655 public:
2656  /// \brief Exception thrown when trying to encrypt plaintext of invalid length
2657  class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
2658  {
2659  public:
2660  InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
2661  };
2662 
2663  /// \brief Encrypt a byte string
2664  /// \param rng a RandomNumberGenerator derived class
2665  /// \param plaintext the plaintext byte buffer
2666  /// \param plaintextLength the size of the plaintext byte buffer
2667  /// \param ciphertext a byte buffer to hold the encrypted string
2668  /// \param parameters a set of NameValuePairs to initialize this object
2669  /// \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
2670  /// \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
2671  /// byte buffer is large enough.
2672  /// \sa PK_Decryptor
2673  virtual void Encrypt(RandomNumberGenerator &rng,
2674  const byte *plaintext, size_t plaintextLength,
2675  byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2676 
2677  /// \brief Create a new encryption filter
2678  /// \param rng a RandomNumberGenerator derived class
2679  /// \param attachment an attached transformation
2680  /// \param parameters a set of NameValuePairs to initialize this object
2681  /// \details \p attachment can be \p NULL. The caller is responsible for deleting the returned pointer.
2682  /// Encoding parameters should be passed in the "EP" channel.
2683  virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
2684  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2685 };
2686 
2687 /// \brief Interface for public-key decryptors
2688 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
2689 {
2690 public:
2691  virtual ~PK_Decryptor() {}
2692 
2693  /// \brief Decrypt a byte string
2694  /// \param rng a RandomNumberGenerator derived class
2695  /// \param ciphertext the encrypted byte buffer
2696  /// \param ciphertextLength the size of the encrypted byte buffer
2697  /// \param plaintext a byte buffer to hold the decrypted string
2698  /// \param parameters a set of NameValuePairs to initialize this object
2699  /// \return the result of the decryption operation
2700  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2701  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2702  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2703  /// is undefined.
2704  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2705  /// byte buffer is large enough
2706  /// \sa PK_Encryptor
2707  virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
2708  const byte *ciphertext, size_t ciphertextLength,
2709  byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2710 
2711  /// \brief Create a new decryption filter
2712  /// \param rng a RandomNumberGenerator derived class
2713  /// \param attachment an attached transformation
2714  /// \param parameters a set of NameValuePairs to initialize this object
2715  /// \return the newly created decryption filter
2716  /// \note the caller is responsible for deleting the returned pointer
2717  virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
2718  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2719 
2720  /// \brief Decrypt a fixed size ciphertext
2721  /// \param rng a RandomNumberGenerator derived class
2722  /// \param ciphertext the encrypted byte buffer
2723  /// \param plaintext a byte buffer to hold the decrypted string
2724  /// \param parameters a set of NameValuePairs to initialize this object
2725  /// \return the result of the decryption operation
2726  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2727  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2728  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2729  /// is undefined.
2730  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2731  /// byte buffer is large enough
2732  /// \sa PK_Encryptor
2733  DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
2734  {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
2735 };
2736 
2737 /// \brief Interface for public-key signers and verifiers
2738 /// \details This class provides an interface common to signers and verifiers for querying scheme properties
2739 /// \sa DL_SignatureSchemeBase, TF_SignatureSchemeBase, DL_SignerBase, TF_SignerBase
2740 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
2741 {
2742 public:
2743  /// \brief Exception throw when the private or public key has a length that can't be used
2744  /// \details InvalidKeyLength() may be thrown by any function in this class if the private
2745  /// or public key has a length that can't be used
2746  class CRYPTOPP_DLL InvalidKeyLength : public Exception
2747  {
2748  public:
2749  InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
2750  };
2751 
2752  /// \brief Exception throw when the private or public key is too short to sign or verify
2753  /// \details KeyTooShort() may be thrown by any function in this class if the private or public
2754  /// key is too short to sign or verify anything
2755  class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
2756  {
2757  public:
2758  KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
2759  };
2760 
2761  virtual ~PK_SignatureScheme() {}
2762 
2763  /// \brief Provides the signature length if it only depends on the key
2764  /// \return the signature length if it only depends on the key, in bytes
2765  /// \details SignatureLength() returns the signature length if it only depends on the key, otherwise 0.
2766  virtual size_t SignatureLength() const =0;
2767 
2768  /// \brief Provides the maximum signature length produced given the length of the recoverable message part
2769  /// \param recoverablePartLength the length of the recoverable message part, in bytes
2770  /// \return the maximum signature length produced for a given length of recoverable message part, in bytes
2771  /// \details MaxSignatureLength() returns the maximum signature length produced given the length of the
2772  /// recoverable message part.
2773  virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
2774  {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
2775 
2776  /// \brief Provides the length of longest message that can be recovered
2777  /// \return the length of longest message that can be recovered, in bytes
2778  /// \details MaxRecoverableLength() returns the length of longest message that can be recovered, or 0 if
2779  /// this signature scheme does not support message recovery.
2780  virtual size_t MaxRecoverableLength() const =0;
2781 
2782  /// \brief Provides the length of longest message that can be recovered from a signature of given length
2783  /// \param signatureLength the length of the signature, in bytes
2784  /// \return the length of longest message that can be recovered from a signature of given length, in bytes
2785  /// \details MaxRecoverableLengthFromSignatureLength() returns the length of longest message that can be
2786  /// recovered from a signature of given length, or 0 if this signature scheme does not support message
2787  /// recovery.
2788  virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
2789 
2790  /// \brief Determines whether a signature scheme requires a random number generator
2791  /// \return true if the signature scheme requires a RandomNumberGenerator() to sign
2792  /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take
2793  /// RandomNumberGenerator().
2794  virtual bool IsProbabilistic() const =0;
2795 
2796  /// \brief Determines whether the non-recoverable message part can be signed
2797  /// \return true if the non-recoverable message part can be signed
2798  virtual bool AllowNonrecoverablePart() const =0;
2799 
2800  /// \brief Determines whether the signature must be input before the message
2801  /// \return true if the signature must be input before the message during verifcation
2802  /// \details if SignatureUpfront() returns true, then you must input the signature before the message
2803  /// during verification. Otherwise you can input the signature at anytime.
2804  virtual bool SignatureUpfront() const {return false;}
2805 
2806  /// \brief Determines whether the recoverable part must be input before the non-recoverable part
2807  /// \return true if the recoverable part must be input before the non-recoverable part during signing
2808  /// \details RecoverablePartFirst() determines whether you must input the recoverable part before the
2809  /// non-recoverable part during signing
2810  virtual bool RecoverablePartFirst() const =0;
2811 };
2812 
2813 /// \brief Interface for accumulating messages to be signed or verified
2814 /// \details Only Update() should be called from the PK_MessageAccumulator() class. No other functions
2815 /// inherited from HashTransformation, like DigestSize() and TruncatedFinal(), should be called.
2816 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
2817 {
2818 public:
2819  /// \warning DigestSize() should not be called on PK_MessageAccumulator
2820  unsigned int DigestSize() const
2821  {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
2822 
2823  /// \warning TruncatedFinal() should not be called on PK_MessageAccumulator
2824  void TruncatedFinal(byte *digest, size_t digestSize)
2825  {
2826  CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
2827  throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
2828  }
2829 };
2830 
2831 /// \brief Interface for public-key signers
2832 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
2833 {
2834 public:
2835  virtual ~PK_Signer() {}
2836 
2837  /// \brief Create a new HashTransformation to accumulate the message to be signed
2838  /// \param rng a RandomNumberGenerator derived class
2839  /// \return a pointer to a PK_MessageAccumulator
2840  /// \details NewSignatureAccumulator() can be used with all signing methods. Sign() will autimatically delete the
2841  /// accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2842  virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
2843 
2844  /// \brief Input a recoverable message to an accumulator
2845  /// \param messageAccumulator a reference to a PK_MessageAccumulator
2846  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2847  /// \param recoverableMessageLength the size of the recoverable message part
2848  virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
2849 
2850  /// \brief Sign and delete the messageAccumulator
2851  /// \param rng a RandomNumberGenerator derived class
2852  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2853  /// \param signature a block of bytes for the signature
2854  /// \return actual signature length
2855  /// \details Sign() deletes the messageAccumulator, even if an exception is thrown.
2856  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2857  virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
2858 
2859  /// \brief Sign and restart messageAccumulator
2860  /// \param rng a RandomNumberGenerator derived class
2861  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2862  /// \param signature a block of bytes for the signature
2863  /// \param restart flag indicating whether the messageAccumulator should be restarted
2864  /// \return actual signature length
2865  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2866  virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
2867 
2868  /// \brief Sign a message
2869  /// \param rng a RandomNumberGenerator derived class
2870  /// \param message a pointer to the message
2871  /// \param messageLen the size of the message to be signed
2872  /// \param signature a block of bytes for the signature
2873  /// \return actual signature length
2874  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2875  virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
2876 
2877  /// \brief Sign a recoverable message
2878  /// \param rng a RandomNumberGenerator derived class
2879  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2880  /// \param recoverableMessageLength the size of the recoverable message part
2881  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2882  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2883  /// \param signature a block of bytes for the signature
2884  /// \return actual signature length
2885  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength(recoverableMessageLength)</tt>
2886  virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
2887  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
2888 };
2889 
2890 /// \brief Interface for public-key signature verifiers
2891 /// \details The Recover* functions throw NotImplemented if the signature scheme does not support
2892 /// message recovery.
2893 /// \details The Verify* functions throw InvalidDataFormat if the scheme does support message
2894 /// recovery and the signature contains a non-empty recoverable message part. The
2895 /// Recover* functions should be used in that case.
2896 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
2897 {
2898 public:
2899  virtual ~PK_Verifier() {}
2900 
2901  /// \brief Create a new HashTransformation to accumulate the message to be verified
2902  /// \return a pointer to a PK_MessageAccumulator
2903  /// \details NewVerificationAccumulator() can be used with all verification methods. Verify() will autimatically delete
2904  /// the accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2905  virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
2906 
2907  /// \brief Input signature into a message accumulator
2908  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2909  /// \param signature the signature on the message
2910  /// \param signatureLength the size of the signature
2911  virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
2912 
2913  /// \brief Check whether messageAccumulator contains a valid signature and message
2914  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2915  /// \return true if the signature is valid, false otherwise
2916  /// \details Verify() deletes the messageAccumulator, even if an exception is thrown.
2917  virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
2918 
2919  /// \brief Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
2920  /// \param messageAccumulator a reference to a PK_MessageAccumulator derived class
2921  /// \return true if the signature is valid, false otherwise
2922  /// \details VerifyAndRestart() restarts the messageAccumulator
2923  virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
2924 
2925  /// \brief Check whether input signature is a valid signature for input message
2926  /// \param message a pointer to the message to be verified
2927  /// \param messageLen the size of the message
2928  /// \param signature a pointer to the signature over the message
2929  /// \param signatureLen the size of the signature
2930  /// \return true if the signature is valid, false otherwise
2931  virtual bool VerifyMessage(const byte *message, size_t messageLen,
2932  const byte *signature, size_t signatureLen) const;
2933 
2934  /// \brief Recover a message from its signature
2935  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2936  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2937  /// \return the result of the verification operation
2938  /// \details Recover() deletes the messageAccumulator, even if an exception is thrown.
2939  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2940  virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
2941 
2942  /// \brief Recover a message from its signature
2943  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2944  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2945  /// \return the result of the verification operation
2946  /// \details RecoverAndRestart() restarts the messageAccumulator
2947  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2948  virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
2949 
2950  /// \brief Recover a message from its signature
2951  /// \param recoveredMessage a pointer for the recovered message
2952  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2953  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2954  /// \param signature the signature on the message
2955  /// \param signatureLength the size of the signature
2956  /// \return the result of the verification operation
2957  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2958  virtual DecodingResult RecoverMessage(byte *recoveredMessage,
2959  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
2960  const byte *signature, size_t signatureLength) const;
2961 };
2962 
2963 /// \brief Interface for domains of simple key agreement protocols
2964 /// \details A key agreement domain is a set of parameters that must be shared
2965 /// by two parties in a key agreement protocol, along with the algorithms
2966 /// for generating key pairs and deriving agreed values.
2967 /// \since Crypto++ 3.0
2968 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
2969 {
2970 public:
2971  virtual ~SimpleKeyAgreementDomain() {}
2972 
2973  /// \brief Provides the size of the agreed value
2974  /// \return size of agreed value produced in this domain
2975  virtual unsigned int AgreedValueLength() const =0;
2976 
2977  /// \brief Provides the size of the private key
2978  /// \return size of private keys in this domain
2979  virtual unsigned int PrivateKeyLength() const =0;
2980 
2981  /// \brief Provides the size of the public key
2982  /// \return size of public keys in this domain
2983  virtual unsigned int PublicKeyLength() const =0;
2984 
2985  /// \brief Generate private key in this domain
2986  /// \param rng a RandomNumberGenerator derived class
2987  /// \param privateKey a byte buffer for the generated private key in this domain
2988  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
2989  virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
2990 
2991  /// \brief Generate a public key from a private key in this domain
2992  /// \param rng a RandomNumberGenerator derived class
2993  /// \param privateKey a byte buffer with the previously generated private key
2994  /// \param publicKey a byte buffer for the generated public key in this domain
2995  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
2996  virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
2997 
2998  /// \brief Generate a private/public key pair
2999  /// \param rng a RandomNumberGenerator derived class
3000  /// \param privateKey a byte buffer for the generated private key in this domain
3001  /// \param publicKey a byte buffer for the generated public key in this domain
3002  /// \details GenerateKeyPair() is equivalent to calling GeneratePrivateKey() and then GeneratePublicKey().
3003  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3004  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
3005  virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3006 
3007  /// \brief Derive agreed value
3008  /// \param agreedValue a byte buffer for the shared secret
3009  /// \param privateKey a byte buffer with your private key in this domain
3010  /// \param otherPublicKey a byte buffer with the other party's public key in this domain
3011  /// \param validateOtherPublicKey a flag indicating if the other party's public key should be validated
3012  /// \return true upon success, false in case of failure
3013  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3014  /// \details The other party's public key is validated by default. If you have previously validated the
3015  /// static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3016  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3017  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3018  /// \pre <tt>COUNTOF(otherPublicKey) == PublicKeyLength()</tt>
3019  virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
3020 };
3021 
3022 /// \brief Interface for domains of authenticated key agreement protocols
3023 /// \details In an authenticated key agreement protocol, each party has two
3024 /// key pairs. The long-lived key pair is called the static key pair,
3025 /// and the short-lived key pair is called the ephemeral key pair.
3026 /// \since Crypto++ 3.0
3027 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3028 {
3029 public:
3030  virtual ~AuthenticatedKeyAgreementDomain() {}
3031 
3032  /// \brief Provides the size of the agreed value
3033  /// \return size of agreed value produced in this domain
3034  virtual unsigned int AgreedValueLength() const =0;
3035 
3036  /// \brief Provides the size of the static private key
3037  /// \return size of static private keys in this domain
3038  virtual unsigned int StaticPrivateKeyLength() const =0;
3039 
3040  /// \brief Provides the size of the static public key
3041  /// \return size of static public keys in this domain
3042  virtual unsigned int StaticPublicKeyLength() const =0;
3043 
3044  /// \brief Generate static private key in this domain
3045  /// \param rng a RandomNumberGenerator derived class
3046  /// \param privateKey a byte buffer for the generated private key in this domain
3047  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3048  virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3049 
3050  /// \brief Generate a static public key from a private key in this domain
3051  /// \param rng a RandomNumberGenerator derived class
3052  /// \param privateKey a byte buffer with the previously generated private key
3053  /// \param publicKey a byte buffer for the generated public key in this domain
3054  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3055  virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3056 
3057  /// \brief Generate a static private/public key pair
3058  /// \param rng a RandomNumberGenerator derived class
3059  /// \param privateKey a byte buffer for the generated private key in this domain
3060  /// \param publicKey a byte buffer for the generated public key in this domain
3061  /// \details GenerateStaticKeyPair() is equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey().
3062  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3063  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3064  virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3065 
3066  /// \brief Provides the size of ephemeral private key
3067  /// \return the size of ephemeral private key in this domain
3068  virtual unsigned int EphemeralPrivateKeyLength() const =0;
3069 
3070  /// \brief Provides the size of ephemeral public key
3071  /// \return the size of ephemeral public key in this domain
3072  virtual unsigned int EphemeralPublicKeyLength() const =0;
3073 
3074  /// \brief Generate ephemeral private key
3075  /// \param rng a RandomNumberGenerator derived class
3076  /// \param privateKey a byte buffer for the generated private key in this domain
3077  /// \pre <tt>COUNTOF(privateKey) == PrivateEphemeralKeyLength()</tt>
3078  virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3079 
3080  /// \brief Generate ephemeral public key
3081  /// \param rng a RandomNumberGenerator derived class
3082  /// \param privateKey a byte buffer for the generated private key in this domain
3083  /// \param publicKey a byte buffer for the generated public key in this domain
3084  /// \pre <tt>COUNTOF(publicKey) == PublicEphemeralKeyLength()</tt>
3085  virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3086 
3087  /// \brief Generate private/public key pair
3088  /// \param rng a RandomNumberGenerator derived class
3089  /// \param privateKey a byte buffer for the generated private key in this domain
3090  /// \param publicKey a byte buffer for the generated public key in this domain
3091  /// \details GenerateEphemeralKeyPair() is equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey()
3092  virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3093 
3094  /// \brief Derive agreed value
3095  /// \param agreedValue a byte buffer for the shared secret
3096  /// \param staticPrivateKey a byte buffer with your static private key in this domain
3097  /// \param ephemeralPrivateKey a byte buffer with your ephemeral private key in this domain
3098  /// \param staticOtherPublicKey a byte buffer with the other party's static public key in this domain
3099  /// \param ephemeralOtherPublicKey a byte buffer with the other party's ephemeral public key in this domain
3100  /// \param validateStaticOtherPublicKey a flag indicating if the other party's public key should be validated
3101  /// \return true upon success, false in case of failure
3102  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3103  /// \details The other party's ephemeral public key is validated by default. If you have previously validated
3104  /// the static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3105  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3106  /// \pre <tt>COUNTOF(staticPrivateKey) == StaticPrivateKeyLength()</tt>
3107  /// \pre <tt>COUNTOF(ephemeralPrivateKey) == EphemeralPrivateKeyLength()</tt>
3108  /// \pre <tt>COUNTOF(staticOtherPublicKey) == StaticPublicKeyLength()</tt>
3109  /// \pre <tt>COUNTOF(ephemeralOtherPublicKey) == EphemeralPublicKeyLength()</tt>
3110  virtual bool Agree(byte *agreedValue,
3111  const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
3112  const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
3113  bool validateStaticOtherPublicKey=true) const =0;
3114 };
3115 
3116 // interface for password authenticated key agreement protocols, not implemented yet
3117 #if 0
3118 /// \brief Interface for protocol sessions
3119 /*! The methods should be called in the following order:
3120 
3121  InitializeSession(rng, parameters); // or call initialize method in derived class
3122  while (true)
3123  {
3124  if (OutgoingMessageAvailable())
3125  {
3126  length = GetOutgoingMessageLength();
3127  GetOutgoingMessage(message);
3128  ; // send outgoing message
3129  }
3130 
3131  if (LastMessageProcessed())
3132  break;
3133 
3134  ; // receive incoming message
3135  ProcessIncomingMessage(message);
3136  }
3137  ; // call methods in derived class to obtain result of protocol session
3138 */
3139 class ProtocolSession
3140 {
3141 public:
3142  /// Exception thrown when an invalid protocol message is processed
3143  class ProtocolError : public Exception
3144  {
3145  public:
3146  ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
3147  };
3148 
3149  /// Exception thrown when a function is called unexpectedly
3150  /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
3151  class UnexpectedMethodCall : public Exception
3152  {
3153  public:
3154  UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
3155  };
3156 
3157  virtual ~ProtocolSession() {}
3158 
3159  ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {}
3160 
3161  virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
3162 
3163  bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
3164  void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
3165 
3166  bool HasValidState() const {return m_validState;}
3167 
3168  virtual bool OutgoingMessageAvailable() const =0;
3169  virtual unsigned int GetOutgoingMessageLength() const =0;
3170  virtual void GetOutgoingMessage(byte *message) =0;
3171 
3172  virtual bool LastMessageProcessed() const =0;
3173  virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
3174 
3175 protected:
3176  void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
3177  void CheckAndHandleInvalidState() const;
3178  void SetValidState(bool valid) {m_validState = valid;}
3179 
3180  RandomNumberGenerator *m_rng;
3181 
3182 private:
3183  bool m_throwOnProtocolError, m_validState;
3184 };
3185 
3186 class KeyAgreementSession : public ProtocolSession
3187 {
3188 public:
3189  virtual ~KeyAgreementSession() {}
3190 
3191  virtual unsigned int GetAgreedValueLength() const =0;
3192  virtual void GetAgreedValue(byte *agreedValue) const =0;
3193 };
3194 
3195 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
3196 {
3197 public:
3198  virtual ~PasswordAuthenticatedKeyAgreementSession() {}
3199 
3200  void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
3201  const byte *myId, unsigned int myIdLength,
3202  const byte *counterPartyId, unsigned int counterPartyIdLength,
3203  const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
3204 };
3205 
3206 /// \brief Password based key agreement domain
3207 /// \since Crypto++ 3.0
3208 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3209 {
3210 public:
3211  virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
3212 
3213  /// return whether the domain parameters stored in this object are valid
3214  virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
3215  {return GetCryptoParameters().Validate(rng, 2);}
3216 
3217  virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
3218  virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
3219 
3220  enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
3221 
3222  virtual bool IsValidRole(unsigned int role) =0;
3223  virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
3224 };
3225 #endif
3226 
3227 /// \brief Exception thrown when an ASN.1 BER decoing error is encountered
3228 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
3229 {
3230 public:
3231  BERDecodeErr() : InvalidArgument("BER decode error") {}
3232  BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
3233 };
3234 
3235 /// \brief Interface for encoding and decoding ASN1 objects
3236 /// \details Each class that derives from ASN1Object should provide a serialization format
3237 /// that controls subobject layout. Most of the time the serialization format is
3238 /// taken from a standard, like P1363 or an RFC.
3239 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
3240 {
3241 public:
3242  virtual ~ASN1Object() {}
3243 
3244  /// \brief Decode this object from a BufferedTransformation
3245  /// \param bt BufferedTransformation object
3246  /// \details Uses Basic Encoding Rules (BER)
3247  virtual void BERDecode(BufferedTransformation &bt) =0;
3248 
3249  /// \brief Encode this object into a BufferedTransformation
3250  /// \param bt BufferedTransformation object
3251  /// \details Uses Distinguished Encoding Rules (DER)
3252  virtual void DEREncode(BufferedTransformation &bt) const =0;
3253 
3254  /// \brief Encode this object into a BufferedTransformation
3255  /// \param bt BufferedTransformation object
3256  /// \details Uses Basic Encoding Rules (BER).
3257  /// \details This may be useful if DEREncode() would be too inefficient.
3258  virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
3259 };
3260 
3261 /// \brief Specifies the build-time version of the library
3262 /// \returns integer representing the build-time version
3263 /// \details LibraryVersion can help detect inadvertent mixing and matching of library
3264 /// versions. When using Crypto++ distributed by a third party, LibraryVersion()
3265 /// records the version of the shared object that was built by the third party.
3266 /// The LibraryVersion() record resides in <tt>cryptlib.o</tt> on Unix compatibles
3267 /// and <tt>cryptlib.obj</tt> on Windows. It does not change when an app links
3268 /// to the library.
3269 /// \details LibraryVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3270 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3271 /// the library version is 5.7 or above. If it is missing, then the library version is
3272 /// 5.6.5 or below.
3273 /// \details The function could be used as shown below.
3274 /// <pre>
3275 /// if (LibraryVersion() != HeaderVersion())
3276 /// {
3277 /// cout << "Potential version mismatch" << endl;
3278 ///
3279 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3280 /// const int lmin = (LibraryVersion() / 10U) % 10;
3281 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3282 /// const int hmin = (HeaderVersion() / 10U) % 10;
3283 ///
3284 /// if(lmaj != hmaj)
3285 /// cout << "Major version mismatch" << endl;
3286 /// else if(lmin != hmin)
3287 /// cout << "Minor version mismatch" << endl;
3288 /// }
3289 /// </pre>
3290 /// \sa HeaderVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3291 /// \since Crypto++ 6.0
3292 extern "C" {
3293  int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT);
3294 } // C linkage
3295 
3296 /// \brief Specifies the runtime version of the library
3297 /// \returns integer representing the runtime version
3298 /// \details HeaderVersion() can help detect inadvertent mixing and matching of library
3299 /// versions. When using Crypto++ distributed by a third party, HeaderVersion()
3300 /// records the version of the headers used by the app when the app is compiled.
3301 /// \details HeaderVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3302 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3303 /// the library version is 5.7 or above. If it is missing, then the library version is
3304 /// 5.6.5 or below.
3305 /// \details The function could be used as shown below.
3306 /// <pre>
3307 /// if (LibraryVersion() != HeaderVersion())
3308 /// {
3309 /// cout << "Potential version mismatch" << endl;
3310 ///
3311 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3312 /// const int lmin = (LibraryVersion() / 10U) % 10;
3313 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3314 /// const int hmin = (HeaderVersion() / 10U) % 10;
3315 ///
3316 /// if(lmaj != hmaj)
3317 /// cout << "Major version mismatch" << endl;
3318 /// else if(lmin != hmin)
3319 /// cout << "Minor version mismatch" << endl;
3320 /// }
3321 /// </pre>
3322 /// \sa LibraryVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3323 /// \since Crypto++ 6.0
3324 extern "C" {
3325 inline int HeaderVersion()
3326 {
3327  return CRYPTOPP_VERSION;
3328 }
3329 } // C linkage
3330 
3331 NAMESPACE_END
3332 
3333 #if CRYPTOPP_MSC_VERSION
3334 # pragma warning(pop)
3335 #endif
3336 
3337 #endif
virtual unsigned int BlockSize() const
Provides the block size of the compression function.
Definition: cryptlib.h:1166
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:158
int HeaderVersion()
Specifies the runtime version of the library.
Definition: cryptlib.h:3325
Exception thrown when invalid crypto material is detected.
Definition: cryptlib.h:2358
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition: cryptlib.h:2437
the cipher is performing decryption
Definition: cryptlib.h:127
const char * DigestSize()
int, in bytes
Definition: argnames.h:79
An invalid argument was detected.
Definition: cryptlib.h:202
void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
Sets or reset the key of this object.
Definition: cryptlib.h:709
unsigned int TagSize() const
Provides the tag size of the hash.
Definition: cryptlib.h:1158
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:1524
Interface for message authentication codes.
Definition: cryptlib.h:1295
ErrorType
Error types or categories.
Definition: cryptlib.h:163
NotImplemented(const std::string &s)
Construct an NotImplemented.
Definition: cryptlib.h:238
CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
Get a named value with type int, with default.
Definition: cryptlib.h:424
Interface for asymmetric algorithms.
Definition: cryptlib.h:2515
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition: cryptlib.h:772
Namespace containing NaCl library functions.
Definition: cryptlib.h:569
virtual bool NeedsPrespecifiedDataLengths() const
Determines if data lengths must be specified prior to inputting data.
Definition: cryptlib.h:1349
Interface for public-key encryptors and decryptors.
Definition: cryptlib.h:2616
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:143
const char * what() const
Retrieves a C-string describing the exception.
Definition: cryptlib.h:186
virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: cryptlib.h:2392
The IV is set by the object.
Definition: cryptlib.h:728
The operating system reported an error.
Definition: cryptlib.h:252
Interface for authenticated encryption modes of operation.
Definition: cryptlib.h:1317
T GetValueWithDefault(const char *name, T defaultValue) const
Get a named value.
Definition: cryptlib.h:392
const std::type_info & GetStoredTypeInfo() const
Provides the stored type.
Definition: cryptlib.h:342
InvalidDataFormat(const std::string &s)
Construct an InvalidDataFormat.
Definition: cryptlib.h:218
virtual void Load(BufferedTransformation &bt)
Loads a key from a BufferedTransformation.
Definition: cryptlib.h:2421
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition: cryptlib.h:2165
Exception(ErrorType errorType, const std::string &s)
Construct a new Exception.
Definition: cryptlib.h:183
virtual void IsolatedInitialize(const NameValuePairs &parameters)
Initialize or reinitialize this object, without signal propagation.
Definition: cryptlib.h:1792
Exception thrown when the object is in the wrong state for the operation.
Definition: cryptlib.h:1325
const CryptoMaterial & GetMaterial() const
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2603
CRYPTOPP_DLL std::string GetValueNames() const
Get a list of value names that can be retrieved.
Definition: cryptlib.h:404
Interface for public-key signers.
Definition: cryptlib.h:2832
Interface for public-key encryptors.
Definition: cryptlib.h:2653
virtual bool CanModifyInput() const
Determines whether input can be modified by the callee.
Definition: cryptlib.h:1702
Converts an enumeration to a type suitable for use as a template parameter.
Definition: cryptlib.h:135
bool GetThisObject(T &object) const
Get a copy of this object or subobject.
Definition: cryptlib.h:357
bool CanUseRandomIVs() const
Determines if the object can use random IVs.
Definition: cryptlib.h:745
CipherDir
Specifies a direction for a cipher to operate.
Definition: cryptlib.h:123
CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const
Get a named value with type word64.
Definition: cryptlib.h:433
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const
Decrypt a fixed size ciphertext.
Definition: cryptlib.h:2733
Flush(true) was called but it can't completely flush its buffers.
Definition: cryptlib.h:242
Thrown when an unexpected type is encountered.
Definition: cryptlib.h:329
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2579
Interface for asymmetric algorithms using private keys.
Definition: cryptlib.h:2572
virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
Updates the hash with additional input and verifies the hash of the current message.
Definition: cryptlib.h:1266
virtual bool IsProbabilistic() const =0
Determines whether a signature scheme requires a random number generator.
ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
Construct a ValueTypeMismatch.
Definition: cryptlib.h:336
virtual bool AllowNonrecoverablePart() const =0
Determines whether the non-recoverable message part can be signed.
virtual unsigned int NumberOfMessagesInThisSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:2079
virtual Clonable * Clone() const
Copies this object.
Definition: cryptlib.h:595
CipherDir GetCipherDirection() const
Provides the direction of the cipher.
Definition: cryptlib.h:941
EnumToType< ByteOrder, LITTLE_ENDIAN_ORDER > LittleEndian
Provides a constant for LittleEndian.
Definition: cryptlib.h:150
Library configuration file.
Interface for random number generators.
Definition: cryptlib.h:1412
Common C++ header files.
void ProcessString(byte *inoutString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1061
size_t messageLength
Recovered message length if isValidCoding is true, undefined otherwise.
Definition: cryptlib.h:303
virtual const PublicKey & GetPublicKey() const
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2567
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1860
virtual size_t SignatureLength() const =0
Provides the signature length if it only depends on the key.
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this hash.
Definition: cryptlib.h:1173
CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
Retrieves a required name/value pair.
Definition: cryptlib.h:483
Interface for buffered transformations.
Definition: cryptlib.h:1627
OS_Error(ErrorType errorType, const std::string &s, const std::string &operation, int errorCode)
Construct an OS_Error.
Definition: cryptlib.h:263
Interface for private keys.
Definition: cryptlib.h:2501
virtual const BufferedTransformation * AttachedTransformation() const
Returns the object immediately attached to this object.
Definition: cryptlib.h:2317
Interface for cloning objects.
Definition: cryptlib.h:585
virtual size_t FixedCiphertextLength() const
Provides the fixed ciphertext length, if one exists.
Definition: cryptlib.h:2642
lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
Copy bytes from this object using an index to another BufferedTransformation.
Definition: cryptlib.h:1998
bool operator==(const OID &lhs, const OID &rhs)
Compare two OIDs for equality.
Data integerity check, such as CRC or MAC, failed.
Definition: cryptlib.h:171
byte order is little-endian
Definition: cryptlib.h:145
Interface for one direction (encryption or decryption) of a block cipher.
Definition: cryptlib.h:1279
CRYPTOPP_DLL RandomNumberGenerator &CRYPTOPP_API NullRNG()
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:401
virtual CRYPTOPP_DLL bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0
Get a named value.
virtual std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition: cryptlib.h:637
void SetWhat(const std::string &s)
Sets the error string for the exception.
Definition: cryptlib.h:190
Interface for objects that can be waited on.
Definition: cryptlib.h:1578
the cipher is performing encryption
Definition: cryptlib.h:125
size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
Input multiple bytes that may be modified by callee.
Definition: cryptlib.h:1711
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: cryptlib.h:2453
const std::type_info & GetRetrievingTypeInfo() const
Provides the retrieveing type.
Definition: cryptlib.h:346
virtual size_t MaxRecoverableLength() const =0
Provides the length of longest message that can be recovered.
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2458
size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
Input a byte buffer for processing on a channel.
Definition: cryptlib.h:2175
virtual bool IsLastBlockSpecial() const
Determines if the last block receives special processing.
Definition: cryptlib.h:1055
bool MessageEnd(int propagation=-1, bool blocking=true)
Signals the end of messages to the object.
Definition: cryptlib.h:1719
Interface for domains of simple key agreement protocols.
Definition: cryptlib.h:2968
virtual unsigned int GetMaxWaitObjectCount() const =0
Maximum number of wait objects that this object can return.
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2582
bool CanUsePredictableIVs() const
Determines if the object can use random but possibly predictable IVs.
Definition: cryptlib.h:750
Exception thrown when a filter does not support named channels.
Definition: cryptlib.h:2153
Returns a decoding results.
Definition: cryptlib.h:277
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: cryptlib.h:2446
Exception thrown when trying to encrypt plaintext of invalid length.
Definition: cryptlib.h:2657
Input data was received that did not conform to expected format.
Definition: cryptlib.h:173
lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
move transferMax bytes of the buffered output to target as input
Definition: cryptlib.h:1960
Interface for public-key decryptors.
Definition: cryptlib.h:2688
virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const &callStack)=0
Retrieves waitable objects.
A method was called which was not implemented.
Definition: cryptlib.h:232
Exception throw when the private or public key is too short to sign or verify.
Definition: cryptlib.h:2755
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1649
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.h:511
virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0
Check this object for errors.
bool operator!=(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition: cryptlib.h:298
virtual void Restart()
Restart the hash.
Definition: cryptlib.h:1148
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition: cryptlib.h:777
unsigned int DigestSize() const
Definition: cryptlib.h:2820
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:673
CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
Get a named value with type word64, with default.
Definition: cryptlib.h:442
Interface for encoding and decoding ASN1 objects.
Definition: cryptlib.h:3239
StreamTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:954
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition: cryptlib.h:784
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:966
void ProcessString(byte *outString, const byte *inString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1069
virtual unsigned int GetOptimalBlockSizeUsed() const
Provides the number of bytes used in the current block when processing at optimal block size.
Definition: cryptlib.h:977
size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
Input multiple bytes that may be modified by callee on a channel.
Definition: cryptlib.h:2185
DecodingResult()
Constructs a DecodingResult.
Definition: cryptlib.h:282
BufferedTransformation()
Construct a BufferedTransformation.
Definition: cryptlib.h:1633
Exception thrown when a filter does not recognize a named channel.
Definition: cryptlib.h:2156
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode.
Definition: cryptlib.h:1287
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
DecodingResult(size_t len)
Constructs a DecodingResult.
Definition: cryptlib.h:286
void ProcessBlock(const byte *inBlock, byte *outBlock) const
Encrypt or decrypt a block.
Definition: cryptlib.h:880
Exception throw when the private or public key has a length that can't be used.
Definition: cryptlib.h:2746
Interface for algorithms that take byte strings as keys.
Definition: cryptlib.h:642
bool operator==(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition: cryptlib.h:292
virtual unsigned int NumberOfMessageSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:2082
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2311
HashTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:1121
CannotFlush(const std::string &s)
Construct an CannotFlush.
Definition: cryptlib.h:248
virtual void SetAutoSignalPropagation(int propagation)
Set propagation of automatically generated and transferred signals.
Definition: cryptlib.h:1854
Interface for asymmetric algorithms using public keys.
Definition: cryptlib.h:2546
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:762
virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0
Provides the length of longest message that can be recovered from a signature of given length.
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:529
Namespace containing testing and benchmark classes.
Definition: cryptlib.h:576
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
Definition: cryptlib.h:1433
bool CanUseStructuredIVs() const
Determines if the object can use structured IVs.
Definition: cryptlib.h:756
Interface for public-key signers and verifiers.
Definition: cryptlib.h:2740
Interface for the data processing portion of stream ciphers.
Definition: cryptlib.h:946
virtual void Detach(BufferedTransformation *newAttachment=NULL)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:2326
const std::string & GetOperation() const
Retrieve the operating system API that reported the error.
Definition: cryptlib.h:267
byte order is big-endian
Definition: cryptlib.h:147
virtual bool Verify(const byte *digest)
Verifies the hash of the current message.
Definition: cryptlib.h:1201
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:620
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:69
virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
Updates the hash with additional input and computes the hash of the current message.
Definition: cryptlib.h:1237
int GetErrorCode() const
Retrieve the error code returned by the operating system.
Definition: cryptlib.h:269
const char * BlockSize()
int, in bytes
Definition: argnames.h:27
virtual bool IsolatedMessageSeriesEnd(bool blocking)
Marks the end of a series of messages, without signal propagation.
Definition: cryptlib.h:1806
const unsigned long INFINITE_TIME
Represents infinite time.
Definition: cryptlib.h:130
ErrorType GetErrorType() const
Retrieves the error type for the exception.
Definition: cryptlib.h:192
void GetRequiredParameter(const char *className, const char *name, T &value) const
Retrieves a required name/value pair.
Definition: cryptlib.h:468
CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition: cryptlib.h:415
Interface for all crypto algorithms.
Definition: cryptlib.h:599
size_t Put(const byte *inString, size_t length, bool blocking=true)
Input a byte buffer for processing.
Definition: cryptlib.h:1659
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2816
unsigned int DefaultIVLength() const
Provides the default size of an IV.
Definition: cryptlib.h:767
A decryption filter encountered invalid ciphertext.
Definition: cryptlib.h:222
Interface for key agreement algorithms.
Definition: cryptlib.h:2593
Exception thrown by objects that have not implemented nonblocking input processing.
Definition: cryptlib.h:1759
virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
Updates the hash with additional input and computes the hash of the current message.
Definition: cryptlib.h:1189
virtual void Seek(lword pos)
Seek to an absolute position.
Definition: cryptlib.h:1087
void ProcessBlock(byte *inoutBlock) const
Encrypt or decrypt a block in place.
Definition: cryptlib.h:889
IV_Requirement
Secure IVs requirements as enumerated values.
Definition: cryptlib.h:720
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2555
void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
Transfer all bytes from this object to another BufferedTransformation.
Definition: cryptlib.h:2064
virtual const CryptoParameters & GetCryptoParameters() const
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2610
Interface for public-key signature verifiers.
Definition: cryptlib.h:2896
virtual bool IsPermutation() const
Determines if the transformation is a permutation.
Definition: cryptlib.h:903
virtual byte * CreateUpdateSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1136
void Shuffle(IT begin, IT end)
Randomly shuffle the specified array.
Definition: cryptlib.h:1488
lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
copy copyMax bytes of the buffered output to target as input
Definition: cryptlib.h:1985
Debugging and diagnostic assertions.
InvalidArgument(const std::string &s)
Construct an InvalidArgument.
Definition: cryptlib.h:208
Interface for hash functions and data processing part of MACs.
Definition: cryptlib.h:1113
Interface for crypto material, such as public and private keys, and crypto parameters.
Definition: cryptlib.h:2354
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1696
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2481
Interface for password based key derivation functions.
Definition: cryptlib.h:1562
CryptoMaterial & AccessMaterial()
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2600
An invalid argument was detected.
Definition: cryptlib.h:167
Interface for generatable crypto material, such as private keys and crypto parameters.
Definition: cryptlib.h:2470
size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
Input multiple bytes for processing and signal the end of a message.
Definition: cryptlib.h:1733
virtual bool RecoverablePartFirst() const =0
Determines whether the recoverable part must be input before the non-recoverable part.
Interface for crypto prameters.
Definition: cryptlib.h:2506
bool GetThisPointer(T *&ptr) const
Get a pointer to this object.
Definition: cryptlib.h:366
CRYPTOPP_DLL BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
Definition: cryptlib.cpp:41
bool isValidCoding
Flag to indicate the decoding is valid.
Definition: cryptlib.h:301
BufferedTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:1638
Namespace containing value name definitions.
Definition: argnames.h:13
BufferedTransformation received a Flush(true) signal but can't flush buffers.
Definition: cryptlib.h:169
void SetErrorType(ErrorType errorType)
Sets the error type for the exceptions.
Definition: cryptlib.h:194
int LibraryVersion(...)
Specifies the build-time version of the library.
Definition: cryptlib.cpp:1009
Interface for public keys.
Definition: cryptlib.h:2496
Crypto++ library namespace.
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:379
Interface for the data processing part of block ciphers.
Definition: cryptlib.h:856
FlagsForAdvancedProcessBlocks
Bit flags that control AdvancedProcessBlocks() behavior.
Definition: cryptlib.h:916
The IV must be random and unpredictable.
Definition: cryptlib.h:726
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition: cryptlib.h:741
Interface for domains of authenticated key agreement protocols.
Definition: cryptlib.h:3027
virtual bool GetNextMessageSeries()
Retrieve the next message in a series.
Definition: cryptlib.h:2076
void TruncatedFinal(byte *digest, size_t digestSize)
Definition: cryptlib.h:2824
A method was called which was not implemented.
Definition: cryptlib.h:165
unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
Transfer messages from this object to another BufferedTransformation.
Definition: cryptlib.h:2042
byte ProcessByte(byte input)
Encrypt or decrypt a byte.
Definition: cryptlib.h:1075
const std::string AAD_CHANNEL
Channel for additional authenticated data.
Definition: cryptlib.h:520
virtual void BEREncode(BufferedTransformation &bt) const
Encode this object into a BufferedTransformation.
Definition: cryptlib.h:3258
Error reading from input device or writing to output device.
Definition: cryptlib.h:175
virtual void Save(BufferedTransformation &bt) const
Saves a key to a BufferedTransformation.
Definition: cryptlib.h:2404
virtual bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: cryptlib.h:2427
size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
Input multiple bytes for processing and signal the end of a message.
Definition: cryptlib.h:2235
virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes that may be modified by callee.
Definition: cryptlib.h:1754
virtual void Final(byte *digest)
Computes the hash of the current message.
Definition: cryptlib.h:1143
Input data was received that did not conform to expected format.
Definition: cryptlib.h:212
virtual lword MaxFooterLength() const
Provides the the maximum length of AAD.
Definition: cryptlib.h:1342
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this cipher.
Definition: cryptlib.h:973
virtual const PrivateKey & GetPrivateKey() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2589
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2559
virtual size_t MaxSignatureLength(size_t recoverablePartLength=0) const
Provides the maximum signature length produced given the length of the recoverable message part.
Definition: cryptlib.h:2773
static CRYPTOPP_DLL void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
Ensures an expected name and type is present.
Definition: cryptlib.h:454
EnumToType< ByteOrder, BIG_ENDIAN_ORDER > BigEndian
Provides a constant for BigEndian.
Definition: cryptlib.h:152
virtual bool Attachable()
Determines whether the object allows attachment.
Definition: cryptlib.h:2305
virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
Updates the hash with additional input and verifies the hash of the current message.
Definition: cryptlib.h:1217
Namespace containing weak and wounded algorithms.
Definition: arc4.cpp:14
virtual bool SignatureUpfront() const
Determines whether the signature must be input before the message.
Definition: cryptlib.h:2804
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: cryptlib.h:1425
InvalidCiphertext(const std::string &s)
Construct an InvalidCiphertext.
Definition: cryptlib.h:228
Interface for key derivation functions.
Definition: cryptlib.h:1498
virtual size_t FixedMaxPlaintextLength() const
Provides the maximum plaintext length given a fixed ciphertext length.
Definition: cryptlib.h:2649
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition: cryptlib.h:2223
virtual unsigned int MinLastBlockSize() const
Provides the size of the last block.
Definition: cryptlib.h:1022
Interface for retrieving values given their names.
Definition: cryptlib.h:321
Exception thrown when an ASN.1 BER decoing error is encountered.
Definition: cryptlib.h:3228
The IV must be random and possibly predictable.
Definition: cryptlib.h:724
virtual unsigned int OptimalNumberOfParallelBlocks() const
Determines the number of blocks that can be processed in parallel.
Definition: cryptlib.h:913
const std::string & GetWhat() const
Retrieves a string describing the exception.
Definition: cryptlib.h:188