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 /// \sa <A HREF="https://www.cryptopp.com/wiki/RandomNumberGenerator">RandomNumberGenerator</A>
1413 /// on the Crypto++ wiki
1414 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
1415 {
1416 public:
1417  virtual ~RandomNumberGenerator() {}
1418 
1419  /// \brief Update RNG state with additional unpredictable values
1420  /// \param input the entropy to add to the generator
1421  /// \param length the size of the input buffer
1422  /// \throws NotImplemented
1423  /// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy()
1424  /// to test for the ability to use additional entropy.
1425  /// \details If a derived class does not override IncorporateEntropy(), then the base class
1426  /// throws NotImplemented.
1427  virtual void IncorporateEntropy(const byte *input, size_t length)
1428  {
1429  CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
1430  throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
1431  }
1432 
1433  /// \brief Determines if a generator can accept additional entropy
1434  /// \return true if IncorporateEntropy() is implemented
1435  virtual bool CanIncorporateEntropy() const {return false;}
1436 
1437  /// \brief Generate new random byte and return it
1438  /// \return a random 8-bit byte
1439  /// \details Default implementation calls GenerateBlock() with one byte.
1440  /// \details All generated values are uniformly distributed over the range specified within the
1441  /// the constraints of a particular generator.
1442  virtual byte GenerateByte();
1443 
1444  /// \brief Generate new random bit and return it
1445  /// \return a random bit
1446  /// \details The default implementation calls GenerateByte() and return its lowest bit.
1447  /// \details All generated values are uniformly distributed over the range specified within the
1448  /// the constraints of a particular generator.
1449  virtual unsigned int GenerateBit();
1450 
1451  /// \brief Generate a random 32 bit word in the range min to max, inclusive
1452  /// \param min the lower bound of the range
1453  /// \param max the upper bound of the range
1454  /// \return a random 32-bit word
1455  /// \details The default implementation calls Crop() on the difference between max and
1456  /// min, and then returns the result added to min.
1457  /// \details All generated values are uniformly distributed over the range specified within the
1458  /// the constraints of a particular generator.
1459  virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL);
1460 
1461  /// \brief Generate random array of bytes
1462  /// \param output the byte buffer
1463  /// \param size the length of the buffer, in bytes
1464  /// \details All generated values are uniformly distributed over the range specified within the
1465  /// the constraints of a particular generator.
1466  /// \note A derived generator \a must override either GenerateBlock() or
1467  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1468  virtual void GenerateBlock(byte *output, size_t size);
1469 
1470  /// \brief Generate random bytes into a BufferedTransformation
1471  /// \param target the BufferedTransformation object which receives the bytes
1472  /// \param channel the channel on which the bytes should be pumped
1473  /// \param length the number of bytes to generate
1474  /// \details The default implementation calls GenerateBlock() and pumps the result into
1475  /// the DEFAULT_CHANNEL of the target.
1476  /// \details All generated values are uniformly distributed over the range specified within the
1477  /// the constraints of a particular generator.
1478  /// \note A derived generator \a must override either GenerateBlock() or
1479  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1480  virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
1481 
1482  /// \brief Generate and discard n bytes
1483  /// \param n the number of bytes to generate and discard
1484  virtual void DiscardBytes(size_t n);
1485 
1486  /// \brief Randomly shuffle the specified array
1487  /// \param begin an iterator to the first element in the array
1488  /// \param end an iterator beyond the last element in the array
1489  /// \details The resulting permutation is uniformly distributed.
1490  template <class IT> void Shuffle(IT begin, IT end)
1491  {
1492  // TODO: What happens if there are more than 2^32 elements?
1493  for (; begin != end; ++begin)
1494  std::iter_swap(begin, begin + GenerateWord32(0, static_cast<word32>(end-begin-1)));
1495  }
1496 };
1497 
1498 /// \brief Interface for key derivation functions
1499 /// \since Crypto++ 7.0
1500 /// \sa <A HREF="https://www.cryptopp.com/wiki/KeyDerivationFunction">KeyDerivationFunction</A>
1501 /// on the Crypto++ wiki
1502 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm
1503 {
1504 public:
1505  virtual ~KeyDerivationFunction() {}
1506 
1507  /// \brief Provides the name of this algorithm
1508  /// \return the standard algorithm name
1509  virtual std::string AlgorithmName() const =0;
1510 
1511  /// \brief Determine minimum number of bytes
1512  /// \returns Minimum number of bytes which can be derived
1513  virtual size_t MinDerivedKeyLength() const;
1514 
1515  /// \brief Determine maximum number of bytes
1516  /// \returns Maximum number of bytes which can be derived
1517  virtual size_t MaxDerivedKeyLength() const;
1518 
1519  /// \brief Returns a valid key length for the derivation function
1520  /// \param keylength the size of the derived key, in bytes
1521  /// \returns the valid key length, in bytes
1522  virtual size_t GetValidDerivedLength(size_t keylength) const =0;
1523 
1524  /// \brief Returns whether keylength is a valid key length
1525  /// \param keylength the requested keylength
1526  /// \return true if the derived keylength is valid, false otherwise
1527  /// \details Internally the function calls GetValidKeyLength()
1528  virtual bool IsValidDerivedLength(size_t keylength) const {
1529  return keylength == GetValidDerivedLength(keylength);
1530  }
1531 
1532  /// \brief Derive a key from a seed
1533  /// \param derived the derived output buffer
1534  /// \param derivedLen the size of the derived buffer, in bytes
1535  /// \param secret the seed input buffer
1536  /// \param secretLen the size of the secret buffer, in bytes
1537  /// \param params additional initialization parameters to configure this object
1538  /// \returns the number of iterations performed
1539  /// \throws InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme
1540  /// \details DeriveKey() provides a standard interface to derive a key from
1541  /// a secret seed and other parameters. Each class that derives from KeyDerivationFunction
1542  /// provides an overload that accepts most parameters used by the derivation function.
1543  /// \details the number of iterations performed by DeriveKey() may be 1. For example, a
1544  /// scheme like HKDF does not use the iteration count so it returns 1.
1545  virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params = g_nullNameValuePairs) const =0;
1546 
1547  /// \brief Set or change parameters
1548  /// \param params additional initialization parameters to configure this object
1549  /// \details SetParameters() is useful for setting common parameters when an object is
1550  /// reused. Some derivation function classes may choose to implement it.
1551  virtual void SetParameters(const NameValuePairs& params);
1552 
1553 protected:
1554  /// \brief Returns the base class Algorithm
1555  /// \return the base class Algorithm
1556  virtual const Algorithm & GetAlgorithm() const =0;
1557 
1558  /// \brief Validates the derived key length
1559  /// \param length the size of the derived key material, in bytes
1560  /// \throws InvalidKeyLength if the key length is invalid
1561  void ThrowIfInvalidDerivedKeyLength(size_t length) const;
1562 };
1563 
1564 /// \brief Interface for password based key derivation functions
1565 /// \since Crypto++ 7.0
1567 {
1568 };
1569 
1570 /// \brief Random Number Generator that does not produce random numbers
1571 /// \return reference that can be passed to functions that require a RandomNumberGenerator
1572 /// \details NullRNG() returns a reference that can be passed to functions that require a
1573 /// RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented
1574 /// when a generation function is called.
1575 /// \sa ClassNullRNG, PK_SignatureScheme::IsProbabilistic()
1576 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
1577 
1578 class WaitObjectContainer;
1579 class CallStack;
1580 
1581 /// \brief Interface for objects that can be waited on.
1582 class CRYPTOPP_NO_VTABLE Waitable
1583 {
1584 public:
1585  virtual ~Waitable() {}
1586 
1587  /// \brief Maximum number of wait objects that this object can return
1588  /// \return the maximum number of wait objects
1589  virtual unsigned int GetMaxWaitObjectCount() const =0;
1590 
1591  /// \brief Retrieves waitable objects
1592  /// \param container the wait container to receive the references to the objects.
1593  /// \param callStack CallStack() object used to select waitable objects
1594  /// \details GetWaitObjects() is usually called in one of two ways. First, it can
1595  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1596  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1597  /// parameter, it can be called like
1598  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1599  virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
1600 
1601  /// \brief Wait on this object
1602  /// \return true if the wait succeeded, false otherwise
1603  /// \details Wait() is the same as creating an empty container, calling GetWaitObjects(), and then calling
1604  /// Wait() on the container.
1605  bool Wait(unsigned long milliseconds, CallStack const& callStack);
1606 };
1607 
1608 /// \brief Interface for buffered transformations
1609 /// \details BufferedTransformation is a generalization of BlockTransformation,
1610 /// StreamTransformation and HashTransformation.
1611 /// \details A buffered transformation is an object that takes a stream of bytes as input (this may
1612 /// be done in stages), does some computation on them, and then places the result into an internal
1613 /// buffer for later retrieval. Any partial result already in the output buffer is not modified
1614 /// by further input.
1615 /// \details If a method takes a "blocking" parameter, and you pass false for it, then the method
1616 /// will return before all input has been processed if the input cannot be processed without waiting
1617 /// (for network buffers to become available, for example). In this case the method will return true
1618 /// or a non-zero integer value. When this happens you must continue to call the method with the same
1619 /// parameters until it returns false or zero, before calling any other method on it or attached
1620 /// /p BufferedTransformation. The integer return value in this case is approximately
1621 /// the number of bytes left to be processed, and can be used to implement a progress bar.
1622 /// \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on
1623 /// the signal to attached BufferedTransformation objects, with propagation decremented at each
1624 /// step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation.
1625 /// \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual
1626 /// number of bytes retrieved, which is the lesser of the request number and MaxRetrievable().
1627 /// \details \a Most of the input functions, like Put() and PutWord32(), return the number of
1628 /// bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value
1629 /// means bytes remain to be processed.
1630 /// \nosubgrouping
1631 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
1632 {
1633 public:
1634  virtual ~BufferedTransformation() {}
1635 
1636  /// \brief Construct a BufferedTransformation
1638 
1639  /// \brief Provides a reference to this object
1640  /// \return A reference to this object
1641  /// \details Useful for passing a temporary object to a function that takes a non-const reference
1642  BufferedTransformation& Ref() {return *this;}
1643 
1644  /// \name INPUT
1645  //@{
1646 
1647  /// \brief Input a byte for processing
1648  /// \param inByte the 8-bit byte (octet) to be processed.
1649  /// \param blocking specifies whether the object should block when processing input.
1650  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1651  /// 0 indicates all bytes were processed.
1652  /// \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>.
1653  size_t Put(byte inByte, bool blocking=true)
1654  {return Put(&inByte, 1, blocking);}
1655 
1656  /// \brief Input a byte buffer for processing
1657  /// \param inString the byte buffer to process
1658  /// \param length the size of the string, in bytes
1659  /// \param blocking specifies whether the object should block when processing input
1660  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1661  /// 0 indicates all bytes were processed.
1662  /// \details Internally, Put() calls Put2().
1663  size_t Put(const byte *inString, size_t length, bool blocking=true)
1664  {return Put2(inString, length, 0, blocking);}
1665 
1666  /// Input a 16-bit word for processing.
1667  /// \param value the 16-bit value to be processed
1668  /// \param order the ByteOrder of the value to be processed.
1669  /// \param blocking specifies whether the object should block when processing input
1670  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1671  /// 0 indicates all bytes were processed.
1672  size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1673 
1674  /// Input a 32-bit word for processing.
1675  /// \param value the 32-bit value to be processed.
1676  /// \param order the ByteOrder of the value to be processed.
1677  /// \param blocking specifies whether the object should block when processing input.
1678  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1679  /// 0 indicates all bytes were processed.
1680  size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1681 
1682  /// Input a 64-bit word for processing.
1683  /// \param value the 64-bit value to be processed.
1684  /// \param order the ByteOrder of the value to be processed.
1685  /// \param blocking specifies whether the object should block when processing input.
1686  /// \return the number of bytes that remain in the block (i.e., bytes not processed).
1687  /// 0 indicates all bytes were processed.
1688  size_t PutWord64(word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1689 
1690  /// \brief Request space which can be written into by the caller
1691  /// \param size the requested size of the buffer
1692  /// \return byte pointer to the space to input data
1693  /// \details The purpose of this method is to help avoid extra memory allocations.
1694  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1695  /// size is the requested size of the buffer. When the call returns, size is the size of
1696  /// the array returned to the caller.
1697  /// \details The base class implementation sets size to 0 and returns NULL.
1698  /// \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
1699  /// an ArraySink, the pointer to the array is returned and the size is remaining size.
1700  virtual byte * CreatePutSpace(size_t &size)
1701  {size=0; return NULLPTR;}
1702 
1703  /// \brief Determines whether input can be modified by the callee
1704  /// \return true if input can be modified, false otherwise
1705  /// \details The base class implementation returns false.
1706  virtual bool CanModifyInput() const
1707  {return false;}
1708 
1709  /// \brief Input multiple bytes that may be modified by callee.
1710  /// \param inString the byte buffer to process
1711  /// \param length the size of the string, in bytes
1712  /// \param blocking specifies whether the object should block when processing input
1713  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1714  /// bytes were processed.
1715  size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
1716  {return PutModifiable2(inString, length, 0, blocking);}
1717 
1718  /// \brief Signals the end of messages to the object
1719  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1720  /// \param blocking specifies whether the object should block when processing input
1721  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1722  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1723  bool MessageEnd(int propagation=-1, bool blocking=true)
1724  {return !!Put2(NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
1725 
1726  /// \brief Input multiple bytes for processing and signal the end of a message
1727  /// \param inString the byte buffer to process
1728  /// \param length the size of the string, in bytes
1729  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1730  /// \param blocking specifies whether the object should block when processing input
1731  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1732  /// bytes were processed.
1733  /// \details Internally, PutMessageEnd() calls Put2() with a modified propagation to
1734  /// ensure all attached transformations finish processing the message.
1735  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1736  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1737  size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
1738  {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
1739 
1740  /// \brief Input multiple bytes for processing
1741  /// \param inString the byte buffer to process
1742  /// \param length the size of the string, in bytes
1743  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
1744  /// \param blocking specifies whether the object should block when processing input
1745  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1746  /// bytes were processed.
1747  /// \details Derived classes must implement Put2().
1748  virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
1749 
1750  /// \brief Input multiple bytes that may be modified by callee.
1751  /// \param inString the byte buffer to process.
1752  /// \param length the size of the string, in bytes.
1753  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
1754  /// \param blocking specifies whether the object should block when processing input.
1755  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1756  /// bytes were processed.
1757  /// \details Internally, PutModifiable2() calls Put2().
1758  virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
1759  {return Put2(inString, length, messageEnd, blocking);}
1760 
1761  /// \brief Exception thrown by objects that have \a not implemented nonblocking input processing
1762  /// \details BlockingInputOnly inherits from NotImplemented
1764  {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
1765  //@}
1766 
1767  /// \name WAITING
1768  //@{
1769  /// \brief Retrieves the maximum number of waitable objects
1770  unsigned int GetMaxWaitObjectCount() const;
1771 
1772  /// \brief Retrieves waitable objects
1773  /// \param container the wait container to receive the references to the objects
1774  /// \param callStack CallStack() object used to select waitable objects
1775  /// \details GetWaitObjects is usually called in one of two ways. First, it can
1776  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1777  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1778  /// parameter, it can be called like
1779  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1780  void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
1781  //@} // WAITING
1782 
1783  /// \name SIGNALS
1784  //@{
1785 
1786  /// \brief Initialize or reinitialize this object, without signal propagation
1787  /// \param parameters a set of NameValuePairs to initialize this object
1788  /// \throws NotImplemented
1789  /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
1790  /// number of arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1791  /// all possible combintations of configurable parameters.
1792  /// \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization
1793  /// should be propagated, then use the Initialize() function.
1794  /// \details If a derived class does not override IsolatedInitialize(), then the base class throws
1795  /// NotImplemented.
1796  virtual void IsolatedInitialize(const NameValuePairs &parameters) {
1797  CRYPTOPP_UNUSED(parameters);
1798  throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
1799  }
1800 
1801  /// \brief Flushes data buffered by this object, without signal propagation
1802  /// \param hardFlush indicates whether all data should be flushed
1803  /// \param blocking specifies whether the object should block when processing input
1804  /// \note hardFlush must be used with care
1805  virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
1806 
1807  /// \brief Marks the end of a series of messages, without signal propagation
1808  /// \param blocking specifies whether the object should block when completing the processing on
1809  /// the current series of messages
1810  virtual bool IsolatedMessageSeriesEnd(bool blocking)
1811  {CRYPTOPP_UNUSED(blocking); return false;}
1812 
1813  /// \brief Initialize or reinitialize this object, with signal propagation
1814  /// \param parameters a set of NameValuePairs to initialize or reinitialize this object
1815  /// \param propagation the number of attached transformations the Initialize() signal should be passed
1816  /// \details Initialize() is used to initialize or reinitialize an object using a variable number of
1817  /// arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1818  /// all possible combintations of configurable parameters.
1819  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1820  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1821  virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
1822 
1823  /// \brief Flush buffered input and/or output, with signal propagation
1824  /// \param hardFlush is used to indicate whether all data should be flushed
1825  /// \param propagation the number of attached transformations the Flush()
1826  /// signal should be passed
1827  /// \param blocking specifies whether the object should block when processing
1828  /// input
1829  /// \details propagation count includes this object. Setting propagation to
1830  /// <tt>1</tt> means this object only. Setting propagation to <tt>-1</tt>
1831  /// means unlimited propagation.
1832  /// \note Hard flushes must be used with care. It means try to process and
1833  /// output everything, even if there may not be enough data to complete the
1834  /// action. For example, hard flushing a HexDecoder would cause an error if
1835  /// you do it after inputing an odd number of hex encoded characters.
1836  /// \note For some types of filters, like ZlibDecompressor, hard flushes can
1837  /// only be done at "synchronization points". These synchronization points
1838  /// are positions in the data stream that are created by hard flushes on the
1839  /// corresponding reverse filters, in this example ZlibCompressor. This is
1840  /// useful when zlib compressed data is moved across a network in packets
1841  /// and compression state is preserved across packets, as in the SSH2 protocol.
1842  virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
1843 
1844  /// \brief Marks the end of a series of messages, with signal propagation
1845  /// \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
1846  /// \param blocking specifies whether the object should block when processing input
1847  /// \details Each object that receives the signal will perform its processing, decrement
1848  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
1849  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1850  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1851  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
1852  virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
1853 
1854  /// \brief Set propagation of automatically generated and transferred signals
1855  /// \param propagation then new value
1856  /// \details Setting propagation to <tt>0</tt> means do not automatically generate signals. Setting
1857  /// propagation to <tt>-1</tt> means unlimited propagation.
1858  virtual void SetAutoSignalPropagation(int propagation)
1859  {CRYPTOPP_UNUSED(propagation);}
1860 
1861  /// \brief Retrieve automatic signal propagation value
1862  /// \return the number of attached transformations the signal is propagated to. 0 indicates
1863  /// the signal is only witnessed by this object
1864  virtual int GetAutoSignalPropagation() const {return 0;}
1865 public:
1866 
1867  /// \name RETRIEVAL OF ONE MESSAGE
1868  //@{
1869 
1870  /// \brief Provides the number of bytes ready for retrieval
1871  /// \return the number of bytes ready for retrieval
1872  /// \details All retrieval functions return the actual number of bytes retrieved, which is
1873  /// the lesser of the request number and MaxRetrievable()
1874  virtual lword MaxRetrievable() const;
1875 
1876  /// \brief Determines whether bytes are ready for retrieval
1877  /// \returns true if bytes are available for retrieval, false otherwise
1878  virtual bool AnyRetrievable() const;
1879 
1880  /// \brief Retrieve a 8-bit byte
1881  /// \param outByte the 8-bit value to be retrieved
1882  /// \return the number of bytes consumed during the call.
1883  /// \details Use the return value of Get to detect short reads.
1884  virtual size_t Get(byte &outByte);
1885 
1886  /// \brief Retrieve a block of bytes
1887  /// \param outString a block of bytes
1888  /// \param getMax the number of bytes to Get
1889  /// \return the number of bytes consumed during the call.
1890  /// \details Use the return value of Get to detect short reads.
1891  virtual size_t Get(byte *outString, size_t getMax);
1892 
1893  /// \brief Peek a 8-bit byte
1894  /// \param outByte the 8-bit value to be retrieved
1895  /// \return the number of bytes read during the call.
1896  /// \details Peek does not remove bytes from the object. Use the return value of
1897  /// Get() to detect short reads.
1898  virtual size_t Peek(byte &outByte) const;
1899 
1900  /// \brief Peek a block of bytes
1901  /// \param outString a block of bytes
1902  /// \param peekMax the number of bytes to Peek
1903  /// \return the number of bytes read during the call.
1904  /// \details Peek does not remove bytes from the object. Use the return value of
1905  /// Peek() to detect short reads.
1906  virtual size_t Peek(byte *outString, size_t peekMax) const;
1907 
1908  /// \brief Retrieve a 16-bit word
1909  /// \param value the 16-bit value to be retrieved
1910  /// \param order the ByteOrder of the value to be processed.
1911  /// \return the number of bytes consumed during the call.
1912  /// \details Use the return value of GetWord16() to detect short reads.
1913  size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1914 
1915  /// \brief Retrieve a 32-bit word
1916  /// \param value the 32-bit value to be retrieved
1917  /// \param order the ByteOrder of the value to be processed.
1918  /// \return the number of bytes consumed during the call.
1919  /// \details Use the return value of GetWord32() to detect short reads.
1920  size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1921 
1922  /// \brief Retrieve a 64-bit word
1923  /// \param value the 64-bit value to be retrieved
1924  /// \param order the ByteOrder of the value to be processed.
1925  /// \return the number of bytes consumed during the call.
1926  /// \details Use the return value of GetWord64() to detect short reads.
1927  /// \since Crypto++ 8.3
1928  size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1929 
1930  /// \brief Peek a 16-bit word
1931  /// \param value the 16-bit value to be retrieved
1932  /// \param order the ByteOrder of the value to be processed.
1933  /// \return the number of bytes consumed during the call.
1934  /// \details Peek does not consume bytes in the stream. Use the return value
1935  /// of PeekWord16() to detect short reads.
1936  size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1937 
1938  /// \brief Peek a 32-bit word
1939  /// \param value the 32-bit value to be retrieved
1940  /// \param order the ByteOrder of the value to be processed.
1941  /// \return the number of bytes consumed during the call.
1942  /// \details Peek does not consume bytes in the stream. Use the return value
1943  /// of PeekWord32() to detect short reads.
1944  size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1945 
1946  /// \brief Peek a 64-bit word
1947  /// \param value the 64-bit value to be retrieved
1948  /// \param order the ByteOrder of the value to be processed.
1949  /// \return the number of bytes consumed during the call.
1950  /// \details Peek does not consume bytes in the stream. Use the return value
1951  /// of PeekWord64() to detect short reads.
1952  /// \since Crypto++ 8.3
1953  size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1954 
1955  /// move transferMax bytes of the buffered output to target as input
1956 
1957  /// \brief Transfer bytes from this object to another BufferedTransformation
1958  /// \param target the destination BufferedTransformation
1959  /// \param transferMax the number of bytes to transfer
1960  /// \param channel the channel on which the transfer should occur
1961  /// \return the number of bytes transferred during the call.
1962  /// \details TransferTo removes bytes from this object and moves them to the destination.
1963  /// \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2().
1964  lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
1965  {TransferTo2(target, transferMax, channel); return transferMax;}
1966 
1967  /// \brief Discard skipMax bytes from the output buffer
1968  /// \param skipMax the number of bytes to discard
1969  /// \details Skip() discards bytes from the output buffer, which is the AttachedTransformation(), if present.
1970  /// The function always returns the parameter <tt>skipMax</tt>.
1971  /// \details If you want to skip bytes from a Source, then perform the following.
1972  /// <pre>
1973  /// StringSource ss(str, false, new Redirector(TheBitBucket()));
1974  /// ss.Pump(10); // Skip 10 bytes from Source
1975  /// ss.Detach(new FilterChain(...));
1976  /// ss.PumpAll();
1977  /// </pre>
1978  virtual lword Skip(lword skipMax=LWORD_MAX);
1979 
1980  /// copy copyMax bytes of the buffered output to target as input
1981 
1982  /// \brief Copy bytes from this object to another BufferedTransformation
1983  /// \param target the destination BufferedTransformation
1984  /// \param copyMax the number of bytes to copy
1985  /// \param channel the channel on which the transfer should occur
1986  /// \return the number of bytes copied during the call.
1987  /// \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
1988  /// \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2().
1989  lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1990  {return CopyRangeTo(target, 0, copyMax, channel);}
1991 
1992  /// \brief Copy bytes from this object using an index to another BufferedTransformation
1993  /// \param target the destination BufferedTransformation
1994  /// \param position the 0-based index of the byte stream to begin the copying
1995  /// \param copyMax the number of bytes to copy
1996  /// \param channel the channel on which the transfer should occur
1997  /// \return the number of bytes copied during the call.
1998  /// \details CopyTo copies bytes from this object to the destination. The bytes remain in this
1999  /// object. Copying begins at the index position in the current stream, and not from an absolute
2000  /// position in the stream.
2001  /// \details The function returns the new position in the stream after transferring the bytes starting at the index.
2002  lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
2003  {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
2004  //@}
2005 
2006  /// \name RETRIEVAL OF MULTIPLE MESSAGES
2007  //@{
2008 
2009  /// \brief Provides the number of bytes ready for retrieval
2010  /// \return the number of bytes ready for retrieval
2011  virtual lword TotalBytesRetrievable() const;
2012 
2013  /// \brief Provides the number of meesages processed by this object
2014  /// \return the number of meesages processed by this object
2015  /// \details NumberOfMessages returns number of times MessageEnd() has been
2016  /// received minus messages retrieved or skipped
2017  virtual unsigned int NumberOfMessages() const;
2018 
2019  /// \brief Determines if any messages are available for retrieval
2020  /// \returns true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
2021  /// \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
2022  virtual bool AnyMessages() const;
2023 
2024  /// \brief Start retrieving the next message
2025  /// \return true if a message is ready for retrieval
2026  /// \details GetNextMessage() returns true if a message is ready for retrieval; false
2027  /// if no more messages exist or this message is not completely retrieved.
2028  virtual bool GetNextMessage();
2029 
2030  /// \brief Skip a number of meessages
2031  /// \return 0 if the requested number of messages was skipped, non-0 otherwise
2032  /// \details SkipMessages() skips count number of messages. If there is an AttachedTransformation()
2033  /// then SkipMessages() is called on the attached transformation. If there is no attached
2034  /// transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo().
2035  virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
2036 
2037  /// \brief Transfer messages from this object to another BufferedTransformation
2038  /// \param target the destination BufferedTransformation
2039  /// \param count the number of messages to transfer
2040  /// \param channel the channel on which the transfer should occur
2041  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2042  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2043  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
2044  /// bytes is returned. TransferMessagesTo() does not proceed to the next message.
2045  /// \details A return value of 0 indicates all messages were successfully transferred.
2046  unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
2047  {TransferMessagesTo2(target, count, channel); return count;}
2048 
2049  /// \brief Copy messages from this object to another BufferedTransformation
2050  /// \param target the destination BufferedTransformation
2051  /// \param count the number of messages to transfer
2052  /// \param channel the channel on which the transfer should occur
2053  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2054  /// \details CopyMessagesTo copies messages from this object and copies them to the destination.
2055  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
2056  /// bytes is returned. CopyMessagesTo() does not proceed to the next message.
2057  /// \details A return value of 0 indicates all messages were successfully copied.
2058  unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
2059 
2060  /// \brief Skip all messages in the series
2061  virtual void SkipAll();
2062 
2063  /// \brief Transfer all bytes from this object to another BufferedTransformation
2064  /// \param target the destination BufferedTransformation
2065  /// \param channel the channel on which the transfer should occur
2066  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2067  /// Internally TransferAllTo() calls TransferAllTo2().
2068  void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
2069  {TransferAllTo2(target, channel);}
2070 
2071  /// \brief Copy messages from this object to another BufferedTransformation
2072  /// \param target the destination BufferedTransformation
2073  /// \param channel the channel on which the transfer should occur
2074  /// \details CopyAllTo copies messages from this object and copies them to the destination.
2075  void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
2076 
2077  /// \brief Retrieve the next message in a series
2078  /// \return true if a message was retreved, false otherwise
2079  /// \details Internally, the base class implementation returns false.
2080  virtual bool GetNextMessageSeries() {return false;}
2081  /// \brief Provides the number of messages in a series
2082  /// \return the number of messages in this series
2083  virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
2084  /// \brief Provides the number of messages in a series
2085  /// \return the number of messages in this series
2086  virtual unsigned int NumberOfMessageSeries() const {return 0;}
2087  //@}
2088 
2089  /// \name NON-BLOCKING TRANSFER OF OUTPUT
2090  //@{
2091 
2092  // upon return, byteCount contains number of bytes that have finished being transferred,
2093  // and returns the number of bytes left in the current transfer block
2094 
2095  /// \brief Transfer bytes from this object to another BufferedTransformation
2096  /// \param target the destination BufferedTransformation
2097  /// \param byteCount the number of bytes to transfer
2098  /// \param channel the channel on which the transfer should occur
2099  /// \param blocking specifies whether the object should block when processing input
2100  /// \return the number of bytes that remain in the transfer block (i.e., bytes not transferred)
2101  /// \details TransferTo2() removes bytes from this object and moves them to the destination.
2102  /// Transfer begins at the index position in the current stream, and not from an absolute
2103  /// position in the stream.
2104  /// \details byteCount is an \a IN and \a OUT parameter. When the call is made,
2105  /// byteCount is the requested size of the transfer. When the call returns, byteCount is
2106  /// the number of bytes that were transferred.
2107  virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
2108 
2109  // upon return, begin contains the start position of data yet to be finished copying,
2110  // and returns the number of bytes left in the current transfer block
2111 
2112  /// \brief Copy bytes from this object to another BufferedTransformation
2113  /// \param target the destination BufferedTransformation
2114  /// \param begin the 0-based index of the first byte to copy in the stream
2115  /// \param end the 0-based index of the last byte to copy in the stream
2116  /// \param channel the channel on which the transfer should occur
2117  /// \param blocking specifies whether the object should block when processing input
2118  /// \return the number of bytes that remain in the copy block (i.e., bytes not copied)
2119  /// \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not
2120  /// removed from this object. Copying begins at the index position in the current stream, and
2121  /// not from an absolute position in the stream.
2122  /// \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the
2123  /// starting position of the copy. When the call returns, begin is the position of the first
2124  /// byte that was \a not copied (which may be different than end). begin can be used for
2125  /// subsequent calls to CopyRangeTo2().
2126  virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
2127 
2128  // upon return, messageCount contains number of messages that have finished being transferred,
2129  // and returns the number of bytes left in the current transfer block
2130 
2131  /// \brief Transfer messages from this object to another BufferedTransformation
2132  /// \param target the destination BufferedTransformation
2133  /// \param messageCount the number of messages to transfer
2134  /// \param channel the channel on which the transfer should occur
2135  /// \param blocking specifies whether the object should block when processing input
2136  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2137  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2138  /// \details messageCount is an \a IN and \a OUT parameter. When the call is made, messageCount is the
2139  /// the number of messages requested to be transferred. When the call returns, messageCount is the
2140  /// number of messages actually transferred.
2141  size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2142 
2143  // returns the number of bytes left in the current transfer block
2144 
2145  /// \brief Transfer all bytes from this object to another BufferedTransformation
2146  /// \param target the destination BufferedTransformation
2147  /// \param channel the channel on which the transfer should occur
2148  /// \param blocking specifies whether the object should block when processing input
2149  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2150  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2151  size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2152  //@}
2153 
2154  /// \name CHANNELS
2155  //@{
2156  /// \brief Exception thrown when a filter does not support named channels
2158  {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
2159  /// \brief Exception thrown when a filter does not recognize a named channel
2161  {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
2162 
2163  /// \brief Input a byte for processing on a channel
2164  /// \param channel the channel to process the data.
2165  /// \param inByte the 8-bit byte (octet) to be processed.
2166  /// \param blocking specifies whether the object should block when processing input.
2167  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2168  /// number of bytes that were not processed.
2169  size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
2170  {return ChannelPut(channel, &inByte, 1, blocking);}
2171 
2172  /// \brief Input a byte buffer for processing on a channel
2173  /// \param channel the channel to process the data
2174  /// \param inString the byte buffer to process
2175  /// \param length the size of the string, in bytes
2176  /// \param blocking specifies whether the object should block when processing input
2177  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2178  /// number of bytes that were not processed.
2179  size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
2180  {return ChannelPut2(channel, inString, length, 0, blocking);}
2181 
2182  /// \brief Input multiple bytes that may be modified by callee on a channel
2183  /// \param channel the channel to process the data.
2184  /// \param inString the byte buffer to process
2185  /// \param length the size of the string, in bytes
2186  /// \param blocking specifies whether the object should block when processing input
2187  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2188  /// number of bytes that were not processed.
2189  size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
2190  {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
2191 
2192  /// \brief Input a 16-bit word for processing on a channel.
2193  /// \param channel the channel to process the data.
2194  /// \param value the 16-bit value to be processed.
2195  /// \param order the ByteOrder of the value to be processed.
2196  /// \param blocking specifies whether the object should block when processing input.
2197  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2198  /// number of bytes that were not processed.
2199  size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2200 
2201  /// \brief Input a 32-bit word for processing on a channel.
2202  /// \param channel the channel to process the data.
2203  /// \param value the 32-bit value to be processed.
2204  /// \param order the ByteOrder of the value to be processed.
2205  /// \param blocking specifies whether the object should block when processing input.
2206  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2207  /// number of bytes that were not processed.
2208  size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2209 
2210  /// \brief Input a 64-bit word for processing on a channel.
2211  /// \param channel the channel to process the data.
2212  /// \param value the 64-bit value to be processed.
2213  /// \param order the ByteOrder of the value to be processed.
2214  /// \param blocking specifies whether the object should block when processing input.
2215  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2216  /// number of bytes that were not processed.
2217  size_t ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2218 
2219  /// \brief Signal the end of a message
2220  /// \param channel the channel to process the data.
2221  /// \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed
2222  /// \param blocking specifies whether the object should block when processing input
2223  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2224  /// number of bytes that were not processed.
2225  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2226  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2227  bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
2228  {return !!ChannelPut2(channel, NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
2229 
2230  /// \brief Input multiple bytes for processing and signal the end of a message
2231  /// \param channel the channel to process the data.
2232  /// \param inString the byte buffer to process
2233  /// \param length the size of the string, in bytes
2234  /// \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed
2235  /// \param blocking specifies whether the object should block when processing input
2236  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2237  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2238  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2239  size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
2240  {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
2241 
2242  /// \brief Request space which can be written into by the caller
2243  /// \param channel the channel to process the data
2244  /// \param size the requested size of the buffer
2245  /// \return a pointer to a memory block with length size
2246  /// \details The purpose of this method is to help avoid extra memory allocations.
2247  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
2248  /// size is the requested size of the buffer. When the call returns, size is the size of
2249  /// the array returned to the caller.
2250  /// \details The base class implementation sets size to 0 and returns NULL.
2251  /// \note Some objects, like ArraySink(), cannot create a space because its fixed. In the case of
2252  /// an ArraySink(), the pointer to the array is returned and the size is remaining size.
2253  virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
2254 
2255  /// \brief Input multiple bytes for processing on a channel.
2256  /// \param channel the channel to process the data.
2257  /// \param inString the byte buffer to process.
2258  /// \param length the size of the string, in bytes.
2259  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
2260  /// \param blocking specifies whether the object should block when processing input.
2261  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2262  virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
2263 
2264  /// \brief Input multiple bytes that may be modified by callee on a channel
2265  /// \param channel the channel to process the data
2266  /// \param inString the byte buffer to process
2267  /// \param length the size of the string, in bytes
2268  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
2269  /// \param blocking specifies whether the object should block when processing input
2270  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2271  virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
2272 
2273  /// \brief Flush buffered input and/or output on a channel
2274  /// \param channel the channel to flush the data
2275  /// \param hardFlush is used to indicate whether all data should be flushed
2276  /// \param propagation the number of attached transformations the ChannelFlush() signal should be passed
2277  /// \param blocking specifies whether the object should block when processing input
2278  /// \return true of the Flush was successful
2279  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2280  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2281  virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
2282 
2283  /// \brief Marks the end of a series of messages on a channel
2284  /// \param channel the channel to signal the end of a series of messages
2285  /// \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed
2286  /// \param blocking specifies whether the object should block when processing input
2287  /// \details Each object that receives the signal will perform its processing, decrement
2288  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
2289  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2290  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2291  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
2292  virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
2293 
2294  /// \brief Sets the default retrieval channel
2295  /// \param channel the channel to signal the end of a series of messages
2296  /// \note this function may not be implemented in all objects that should support it.
2297  virtual void SetRetrievalChannel(const std::string &channel);
2298  //@}
2299 
2300  /// \name ATTACHMENT
2301  /// \details Some BufferedTransformation objects (e.g. Filter objects) allow other BufferedTransformation objects to be
2302  /// attached. When this is done, the first object instead of buffering its output, sends that output to the attached
2303  /// object as input. The entire attachment chain is deleted when the anchor object is destructed.
2304 
2305  //@{
2306  /// \brief Determines whether the object allows attachment
2307  /// \return true if the object allows an attachment, false otherwise
2308  /// \details Sources and Filters will returns true, while Sinks and other objects will return false.
2309  virtual bool Attachable() {return false;}
2310 
2311  /// \brief Returns the object immediately attached to this object
2312  /// \return the attached transformation
2313  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2314  /// version of AttachedTransformation() always returns NULL.
2315  virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;}
2316 
2317  /// \brief Returns the object immediately attached to this object
2318  /// \return the attached transformation
2319  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2320  /// version of AttachedTransformation() always returns NULL.
2322  {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
2323 
2324  /// \brief Delete the current attachment chain and attach a new one
2325  /// \param newAttachment the new BufferedTransformation to attach
2326  /// \throws NotImplemented
2327  /// \details Detach() deletes the current attachment chain and replace it with an optional newAttachment
2328  /// \details If a derived class does not override Detach(), then the base class throws
2329  /// NotImplemented.
2330  virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) {
2331  CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable());
2332  throw NotImplemented("BufferedTransformation: this object is not attachable");
2333  }
2334 
2335  /// \brief Add newAttachment to the end of attachment chain
2336  /// \param newAttachment the attachment to add to the end of the chain
2337  virtual void Attach(BufferedTransformation *newAttachment);
2338  //@}
2339 
2340 protected:
2341  /// \brief Decrements the propagation count while clamping at 0
2342  /// \return the decremented propagation or 0
2343  static int DecrementPropagation(int propagation)
2344  {return propagation != 0 ? propagation - 1 : 0;}
2345 
2346 private:
2347  // for ChannelPutWord16, ChannelPutWord32 and ChannelPutWord64,
2348  // to ensure the buffer isn't deallocated before non-blocking
2349  // operation completes
2350  byte m_buf[8];
2351 };
2352 
2353 /// \brief An input discarding BufferedTransformation
2354 /// \return a reference to a BufferedTransformation object that discards all input
2355 CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
2356 
2357 /// \brief Interface for crypto material
2358 /// \details CryptoMaterial() is an interface for crypto material, such as
2359 /// public keys, private keys and crypto parameters. Derived classes generally
2360 /// do not offer public methods such as GenerateRandom() and
2361 /// GenerateRandomWithKeySize().
2362 /// \sa GeneratableCryptoMaterial()
2363 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
2364 {
2365 public:
2366  /// Exception thrown when invalid crypto material is detected
2367  class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
2368  {
2369  public:
2370  explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
2371  };
2372 
2373  virtual ~CryptoMaterial() {}
2374 
2375  /// \brief Assign values to this object
2376  /// \details This function can be used to create a public key from a private key.
2377  virtual void AssignFrom(const NameValuePairs &source) =0;
2378 
2379  /// \brief Check this object for errors
2380  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2381  /// \param level the level of thoroughness
2382  /// \returns true if the tests succeed, false otherwise
2383  /// \details There are four levels of thoroughness:
2384  /// <ul>
2385  /// <li>0 - using this object won't cause a crash or exception
2386  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
2387  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
2388  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
2389  /// </ul>
2390  /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
2391  /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
2392  /// \sa ThrowIfInvalid()
2393  virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
2394 
2395  /// \brief Check this object for errors
2396  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2397  /// \param level the level of thoroughness
2398  /// \throws InvalidMaterial
2399  /// \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial() if validation fails.
2400  /// \sa Validate()
2401  virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
2402  {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
2403 
2404  /// \brief Saves a key to a BufferedTransformation
2405  /// \param bt the destination BufferedTransformation
2406  /// \throws NotImplemented
2407  /// \details Save() writes the material to a BufferedTransformation.
2408  /// \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
2409  /// includes an object identifier with an algorthm id, like a subjectPublicKeyInfo.
2410  /// \details A "raw" key without the "key info" can be saved using a key's DEREncode() method.
2411  /// \details If a derived class does not override Save(), then the base class throws
2412  /// NotImplemented().
2413  virtual void Save(BufferedTransformation &bt) const
2414  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
2415 
2416  /// \brief Loads a key from a BufferedTransformation
2417  /// \param bt the source BufferedTransformation
2418  /// \throws KeyingErr
2419  /// \details Load() attempts to read material from a BufferedTransformation. If the
2420  /// material is a key that was generated outside the library, then the following
2421  /// usually applies:
2422  /// <ul>
2423  /// <li>the key should be ASN.1 BER encoded
2424  /// <li>the key should be a "key info"
2425  /// </ul>
2426  /// \details "key info" means the key should have an object identifier with an algorthm id,
2427  /// like a subjectPublicKeyInfo.
2428  /// \details To read a "raw" key without the "key info", then call the key's BERDecode() method.
2429  /// \note Load() generally does not check that the key is valid. Call Validate(), if needed.
2430  virtual void Load(BufferedTransformation &bt)
2431  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
2432 
2433  /// \brief Determines whether the object supports precomputation
2434  /// \return true if the object supports precomputation, false otherwise
2435  /// \sa Precompute()
2436  virtual bool SupportsPrecomputation() const {return false;}
2437 
2438  /// \brief Perform precomputation
2439  /// \param precomputationStorage the suggested number of objects for the precompute table
2440  /// \throws NotImplemented
2441  /// \details The exact semantics of Precompute() varies, but it typically means calculate
2442  /// a table of n objects that can be used later to speed up computation.
2443  /// \details If a derived class does not override Precompute(), then the base class throws
2444  /// NotImplemented.
2445  /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation()
2446  virtual void Precompute(unsigned int precomputationStorage) {
2447  CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation());
2448  throw NotImplemented("CryptoMaterial: this object does not support precomputation");
2449  }
2450 
2451  /// \brief Retrieve previously saved precomputation
2452  /// \param storedPrecomputation BufferedTransformation with the saved precomputation
2453  /// \throws NotImplemented
2454  /// \sa SupportsPrecomputation(), Precompute()
2455  virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
2456  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2457 
2458  /// \brief Save precomputation for later use
2459  /// \param storedPrecomputation BufferedTransformation to write the precomputation
2460  /// \throws NotImplemented
2461  /// \sa SupportsPrecomputation(), Precompute()
2462  virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
2463  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2464 
2465  /// \brief Perform a quick sanity check
2466  /// \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users.
2467  void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
2468 
2469 #if defined(__SUNPRO_CC)
2470  // Sun Studio 11/CC 5.8 workaround: it generates incorrect code
2471  // when casting to an empty virtual base class. JW, 2018: It is
2472  // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable
2473  // it everywhere in case it affects SPARC (which we don't test).
2474  char m_sunCCworkaround;
2475 #endif
2476 };
2477 
2478 /// \brief Interface for crypto material
2479 /// \details GeneratableCryptoMaterial() is an interface for crypto material,
2480 /// such as private keys and crypto parameters. Derived classes offer public
2481 /// methods such as GenerateRandom() and GenerateRandomWithKeySize().
2482 /// \sa CryptoMaterial()
2483 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
2484 {
2485 public:
2486  virtual ~GeneratableCryptoMaterial() {}
2487 
2488  /// \brief Generate a random key or crypto parameters
2489  /// \param rng a RandomNumberGenerator to produce keying material
2490  /// \param params additional initialization parameters
2491  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2492  /// \details If a derived class does not override GenerateRandom(), then the base class throws
2493  /// NotImplemented.
2494  virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs) {
2495  CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
2496  throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
2497  }
2498 
2499  /// \brief Generate a random key or crypto parameters
2500  /// \param rng a RandomNumberGenerator to produce keying material
2501  /// \param keySize the size of the key, in bits
2502  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2503  /// \details GenerateRandomWithKeySize calls GenerateRandom() with a NameValuePairs
2504  /// object with only "KeySize"
2505  void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
2506 };
2507 
2508 /// \brief Interface for public keys
2509 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
2510 {
2511 };
2512 
2513 /// \brief Interface for private keys
2514 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
2515 {
2516 };
2517 
2518 /// \brief Interface for crypto prameters
2519 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
2520 {
2521 };
2522 
2523 /// \brief Interface for certificates
2524 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Certificate : virtual public CryptoMaterial
2525 {
2526 };
2527 
2528 /// \brief Interface for asymmetric algorithms
2529 /// \details BERDecode() and DEREncode() were removed under Issue 569
2530 /// and Commit 9b174e84de7a. Programs should use <tt>AccessMaterial().Load(bt)</tt>
2531 /// or <tt>AccessMaterial().Save(bt)</tt> instead.
2532 /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/569">Issue 569</A>
2533 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
2534 {
2535 public:
2536  virtual ~AsymmetricAlgorithm() {}
2537 
2538  /// \brief Retrieves a reference to CryptoMaterial
2539  /// \return a reference to the crypto material
2540  virtual CryptoMaterial & AccessMaterial() =0;
2541 
2542  /// \brief Retrieves a reference to CryptoMaterial
2543  /// \return a const reference to the crypto material
2544  virtual const CryptoMaterial & GetMaterial() const =0;
2545 
2546 #if 0
2547  /// \brief Loads this object from a BufferedTransformation
2548  /// \param bt a BufferedTransformation object
2549  /// \details Use of BERDecode() changed to Load() at Issue 569.
2550  /// \deprecated for backwards compatibility, calls <tt>AccessMaterial().Load(bt)</tt>
2551  void BERDecode(BufferedTransformation &bt)
2552  {AccessMaterial().Load(bt);}
2553 
2554  /// \brief Saves this object to a BufferedTransformation
2555  /// \param bt a BufferedTransformation object
2556  /// \details Use of DEREncode() changed to Save() at Issue 569.
2557  /// \deprecated for backwards compatibility, calls GetMaterial().Save(bt)
2558  void DEREncode(BufferedTransformation &bt) const
2559  {GetMaterial().Save(bt);}
2560 #endif
2561 };
2562 
2563 /// \brief Interface for asymmetric algorithms using public keys
2564 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
2565 {
2566 public:
2567  virtual ~PublicKeyAlgorithm() {}
2568 
2569  // VC60 workaround: no co-variant return type
2570 
2571  /// \brief Retrieves a reference to a Public Key
2572  /// \return a reference to the public key
2574  {return AccessPublicKey();}
2575  /// \brief Retrieves a reference to a Public Key
2576  /// \return a const reference the public key
2577  const CryptoMaterial & GetMaterial() const
2578  {return GetPublicKey();}
2579 
2580  /// \brief Retrieves a reference to a Public Key
2581  /// \return a reference to the public key
2582  virtual PublicKey & AccessPublicKey() =0;
2583  /// \brief Retrieves a reference to a Public Key
2584  /// \return a const reference the public key
2585  virtual const PublicKey & GetPublicKey() const
2586  {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
2587 };
2588 
2589 /// \brief Interface for asymmetric algorithms using private keys
2590 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
2591 {
2592 public:
2593  virtual ~PrivateKeyAlgorithm() {}
2594 
2595  /// \brief Retrieves a reference to a Private Key
2596  /// \return a reference the private key
2597  CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
2598  /// \brief Retrieves a reference to a Private Key
2599  /// \return a const reference the private key
2600  const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
2601 
2602  /// \brief Retrieves a reference to a Private Key
2603  /// \return a reference the private key
2604  virtual PrivateKey & AccessPrivateKey() =0;
2605  /// \brief Retrieves a reference to a Private Key
2606  /// \return a const reference the private key
2607  virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
2608 };
2609 
2610 /// \brief Interface for key agreement algorithms
2611 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
2612 {
2613 public:
2614  virtual ~KeyAgreementAlgorithm() {}
2615 
2616  /// \brief Retrieves a reference to Crypto Parameters
2617  /// \return a reference the crypto parameters
2618  CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
2619  /// \brief Retrieves a reference to Crypto Parameters
2620  /// \return a const reference the crypto parameters
2621  const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
2622 
2623  /// \brief Retrieves a reference to Crypto Parameters
2624  /// \return a reference the crypto parameters
2625  virtual CryptoParameters & AccessCryptoParameters() =0;
2626  /// \brief Retrieves a reference to Crypto Parameters
2627  /// \return a const reference the crypto parameters
2628  virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
2629 };
2630 
2631 /// \brief Interface for public-key encryptors and decryptors
2632 /// \details This class provides an interface common to encryptors and decryptors
2633 /// for querying their plaintext and ciphertext lengths.
2634 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
2635 {
2636 public:
2637  virtual ~PK_CryptoSystem() {}
2638 
2639  /// \brief Provides the maximum length of plaintext for a given ciphertext length
2640  /// \return the maximum size of the plaintext, in bytes
2641  /// \details This function returns 0 if ciphertextLength is not valid (too long or too short).
2642  virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
2643 
2644  /// \brief Calculate the length of ciphertext given length of plaintext
2645  /// \return the maximum size of the ciphertext, in bytes
2646  /// \details This function returns 0 if plaintextLength is not valid (too long).
2647  virtual size_t CiphertextLength(size_t plaintextLength) const =0;
2648 
2649  /// \brief Determines whether this object supports the use of a named parameter
2650  /// \param name the name of the parameter
2651  /// \return true if the parameter name is supported, false otherwise
2652  /// \details Some possible parameter names: EncodingParameters(), KeyDerivationParameters()
2653  /// and others Parameters listed in argnames.h
2654  virtual bool ParameterSupported(const char *name) const =0;
2655 
2656  /// \brief Provides the fixed ciphertext length, if one exists
2657  /// \return the fixed ciphertext length if one exists, otherwise 0
2658  /// \details "Fixed" here means length of ciphertext does not depend on length of plaintext.
2659  /// In this case, it usually does depend on the key length.
2660  virtual size_t FixedCiphertextLength() const {return 0;}
2661 
2662  /// \brief Provides the maximum plaintext length given a fixed ciphertext length
2663  /// \return maximum plaintext length given the fixed ciphertext length, if one exists,
2664  /// otherwise return 0.
2665  /// \details FixedMaxPlaintextLength(0 returns the maximum plaintext length given the fixed ciphertext
2666  /// length, if one exists, otherwise return 0.
2667  virtual size_t FixedMaxPlaintextLength() const {return 0;}
2668 };
2669 
2670 /// \brief Interface for public-key encryptors
2671 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
2672 {
2673 public:
2674  /// \brief Exception thrown when trying to encrypt plaintext of invalid length
2675  class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
2676  {
2677  public:
2678  InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
2679  };
2680 
2681  /// \brief Encrypt a byte string
2682  /// \param rng a RandomNumberGenerator derived class
2683  /// \param plaintext the plaintext byte buffer
2684  /// \param plaintextLength the size of the plaintext byte buffer
2685  /// \param ciphertext a byte buffer to hold the encrypted string
2686  /// \param parameters a set of NameValuePairs to initialize this object
2687  /// \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
2688  /// \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
2689  /// byte buffer is large enough.
2690  /// \sa PK_Decryptor
2691  virtual void Encrypt(RandomNumberGenerator &rng,
2692  const byte *plaintext, size_t plaintextLength,
2693  byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2694 
2695  /// \brief Create a new encryption filter
2696  /// \param rng a RandomNumberGenerator derived class
2697  /// \param attachment an attached transformation
2698  /// \param parameters a set of NameValuePairs to initialize this object
2699  /// \details \p attachment can be \p NULL. The caller is responsible for deleting the returned pointer.
2700  /// Encoding parameters should be passed in the "EP" channel.
2701  virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
2702  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2703 };
2704 
2705 /// \brief Interface for public-key decryptors
2706 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
2707 {
2708 public:
2709  virtual ~PK_Decryptor() {}
2710 
2711  /// \brief Decrypt a byte string
2712  /// \param rng a RandomNumberGenerator derived class
2713  /// \param ciphertext the encrypted byte buffer
2714  /// \param ciphertextLength the size of the encrypted byte buffer
2715  /// \param plaintext a byte buffer to hold the decrypted string
2716  /// \param parameters a set of NameValuePairs to initialize this object
2717  /// \return the result of the decryption operation
2718  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2719  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2720  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2721  /// is undefined.
2722  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2723  /// byte buffer is large enough
2724  /// \sa PK_Encryptor
2725  virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
2726  const byte *ciphertext, size_t ciphertextLength,
2727  byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2728 
2729  /// \brief Create a new decryption filter
2730  /// \param rng a RandomNumberGenerator derived class
2731  /// \param attachment an attached transformation
2732  /// \param parameters a set of NameValuePairs to initialize this object
2733  /// \return the newly created decryption filter
2734  /// \note the caller is responsible for deleting the returned pointer
2735  virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
2736  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2737 
2738  /// \brief Decrypt a fixed size ciphertext
2739  /// \param rng a RandomNumberGenerator derived class
2740  /// \param ciphertext the encrypted byte buffer
2741  /// \param plaintext a byte buffer to hold the decrypted string
2742  /// \param parameters a set of NameValuePairs to initialize this object
2743  /// \return the result of the decryption operation
2744  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2745  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2746  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2747  /// is undefined.
2748  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2749  /// byte buffer is large enough
2750  /// \sa PK_Encryptor
2751  DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
2752  {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
2753 };
2754 
2755 /// \brief Interface for public-key signers and verifiers
2756 /// \details This class provides an interface common to signers and verifiers for querying scheme properties
2757 /// \sa DL_SignatureSchemeBase, TF_SignatureSchemeBase, DL_SignerBase, TF_SignerBase
2758 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
2759 {
2760 public:
2761  /// \brief Exception throw when the private or public key has a length that can't be used
2762  /// \details InvalidKeyLength() may be thrown by any function in this class if the private
2763  /// or public key has a length that can't be used
2764  class CRYPTOPP_DLL InvalidKeyLength : public Exception
2765  {
2766  public:
2767  InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
2768  };
2769 
2770  /// \brief Exception throw when the private or public key is too short to sign or verify
2771  /// \details KeyTooShort() may be thrown by any function in this class if the private or public
2772  /// key is too short to sign or verify anything
2773  class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
2774  {
2775  public:
2776  KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
2777  };
2778 
2779  virtual ~PK_SignatureScheme() {}
2780 
2781  /// \brief Provides the signature length if it only depends on the key
2782  /// \return the signature length if it only depends on the key, in bytes
2783  /// \details SignatureLength() returns the signature length if it only depends on the key, otherwise 0.
2784  virtual size_t SignatureLength() const =0;
2785 
2786  /// \brief Provides the maximum signature length produced given the length of the recoverable message part
2787  /// \param recoverablePartLength the length of the recoverable message part, in bytes
2788  /// \return the maximum signature length produced for a given length of recoverable message part, in bytes
2789  /// \details MaxSignatureLength() returns the maximum signature length produced given the length of the
2790  /// recoverable message part.
2791  virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
2792  {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
2793 
2794  /// \brief Provides the length of longest message that can be recovered
2795  /// \return the length of longest message that can be recovered, in bytes
2796  /// \details MaxRecoverableLength() returns the length of longest message that can be recovered, or 0 if
2797  /// this signature scheme does not support message recovery.
2798  virtual size_t MaxRecoverableLength() const =0;
2799 
2800  /// \brief Provides the length of longest message that can be recovered from a signature of given length
2801  /// \param signatureLength the length of the signature, in bytes
2802  /// \return the length of longest message that can be recovered from a signature of given length, in bytes
2803  /// \details MaxRecoverableLengthFromSignatureLength() returns the length of longest message that can be
2804  /// recovered from a signature of given length, or 0 if this signature scheme does not support message
2805  /// recovery.
2806  virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
2807 
2808  /// \brief Determines whether a signature scheme requires a random number generator
2809  /// \return true if the signature scheme requires a RandomNumberGenerator() to sign
2810  /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take
2811  /// RandomNumberGenerator().
2812  virtual bool IsProbabilistic() const =0;
2813 
2814  /// \brief Determines whether the non-recoverable message part can be signed
2815  /// \return true if the non-recoverable message part can be signed
2816  virtual bool AllowNonrecoverablePart() const =0;
2817 
2818  /// \brief Determines whether the signature must be input before the message
2819  /// \return true if the signature must be input before the message during verifcation
2820  /// \details if SignatureUpfront() returns true, then you must input the signature before the message
2821  /// during verification. Otherwise you can input the signature at anytime.
2822  virtual bool SignatureUpfront() const {return false;}
2823 
2824  /// \brief Determines whether the recoverable part must be input before the non-recoverable part
2825  /// \return true if the recoverable part must be input before the non-recoverable part during signing
2826  /// \details RecoverablePartFirst() determines whether you must input the recoverable part before the
2827  /// non-recoverable part during signing
2828  virtual bool RecoverablePartFirst() const =0;
2829 };
2830 
2831 /// \brief Interface for accumulating messages to be signed or verified
2832 /// \details Only Update() should be called from the PK_MessageAccumulator() class. No other functions
2833 /// inherited from HashTransformation, like DigestSize() and TruncatedFinal(), should be called.
2834 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
2835 {
2836 public:
2837  /// \warning DigestSize() should not be called on PK_MessageAccumulator
2838  unsigned int DigestSize() const
2839  {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
2840 
2841  /// \warning TruncatedFinal() should not be called on PK_MessageAccumulator
2842  void TruncatedFinal(byte *digest, size_t digestSize)
2843  {
2844  CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
2845  throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
2846  }
2847 };
2848 
2849 /// \brief Interface for public-key signers
2850 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
2851 {
2852 public:
2853  virtual ~PK_Signer() {}
2854 
2855  /// \brief Create a new HashTransformation to accumulate the message to be signed
2856  /// \param rng a RandomNumberGenerator derived class
2857  /// \return a pointer to a PK_MessageAccumulator
2858  /// \details NewSignatureAccumulator() can be used with all signing methods. Sign() will autimatically delete the
2859  /// accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2860  virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
2861 
2862  /// \brief Input a recoverable message to an accumulator
2863  /// \param messageAccumulator a reference to a PK_MessageAccumulator
2864  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2865  /// \param recoverableMessageLength the size of the recoverable message part
2866  virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
2867 
2868  /// \brief Sign and delete the messageAccumulator
2869  /// \param rng a RandomNumberGenerator derived class
2870  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2871  /// \param signature a block of bytes for the signature
2872  /// \return actual signature length
2873  /// \details Sign() deletes the messageAccumulator, even if an exception is thrown.
2874  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2875  virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
2876 
2877  /// \brief Sign and restart messageAccumulator
2878  /// \param rng a RandomNumberGenerator derived class
2879  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2880  /// \param signature a block of bytes for the signature
2881  /// \param restart flag indicating whether the messageAccumulator should be restarted
2882  /// \return actual signature length
2883  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2884  virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
2885 
2886  /// \brief Sign a message
2887  /// \param rng a RandomNumberGenerator derived class
2888  /// \param message a pointer to the message
2889  /// \param messageLen the size of the message to be signed
2890  /// \param signature a block of bytes for the signature
2891  /// \return actual signature length
2892  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2893  virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
2894 
2895  /// \brief Sign a recoverable message
2896  /// \param rng a RandomNumberGenerator derived class
2897  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2898  /// \param recoverableMessageLength the size of the recoverable message part
2899  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2900  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2901  /// \param signature a block of bytes for the signature
2902  /// \return actual signature length
2903  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength(recoverableMessageLength)</tt>
2904  virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
2905  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
2906 };
2907 
2908 /// \brief Interface for public-key signature verifiers
2909 /// \details The Recover* functions throw NotImplemented if the signature scheme does not support
2910 /// message recovery.
2911 /// \details The Verify* functions throw InvalidDataFormat if the scheme does support message
2912 /// recovery and the signature contains a non-empty recoverable message part. The
2913 /// Recover* functions should be used in that case.
2914 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
2915 {
2916 public:
2917  virtual ~PK_Verifier() {}
2918 
2919  /// \brief Create a new HashTransformation to accumulate the message to be verified
2920  /// \return a pointer to a PK_MessageAccumulator
2921  /// \details NewVerificationAccumulator() can be used with all verification methods. Verify() will autimatically delete
2922  /// the accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2923  virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
2924 
2925  /// \brief Input signature into a message accumulator
2926  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2927  /// \param signature the signature on the message
2928  /// \param signatureLength the size of the signature
2929  virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
2930 
2931  /// \brief Check whether messageAccumulator contains a valid signature and message
2932  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2933  /// \return true if the signature is valid, false otherwise
2934  /// \details Verify() deletes the messageAccumulator, even if an exception is thrown.
2935  virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
2936 
2937  /// \brief Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
2938  /// \param messageAccumulator a reference to a PK_MessageAccumulator derived class
2939  /// \return true if the signature is valid, false otherwise
2940  /// \details VerifyAndRestart() restarts the messageAccumulator
2941  virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
2942 
2943  /// \brief Check whether input signature is a valid signature for input message
2944  /// \param message a pointer to the message to be verified
2945  /// \param messageLen the size of the message
2946  /// \param signature a pointer to the signature over the message
2947  /// \param signatureLen the size of the signature
2948  /// \return true if the signature is valid, false otherwise
2949  virtual bool VerifyMessage(const byte *message, size_t messageLen,
2950  const byte *signature, size_t signatureLen) const;
2951 
2952  /// \brief Recover a message from its signature
2953  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2954  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2955  /// \return the result of the verification operation
2956  /// \details Recover() deletes the messageAccumulator, even if an exception is thrown.
2957  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2958  virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
2959 
2960  /// \brief Recover a message from its signature
2961  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2962  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2963  /// \return the result of the verification operation
2964  /// \details RecoverAndRestart() restarts the messageAccumulator
2965  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2966  virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
2967 
2968  /// \brief Recover a message from its signature
2969  /// \param recoveredMessage a pointer for the recovered message
2970  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2971  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2972  /// \param signature the signature on the message
2973  /// \param signatureLength the size of the signature
2974  /// \return the result of the verification operation
2975  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2976  virtual DecodingResult RecoverMessage(byte *recoveredMessage,
2977  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
2978  const byte *signature, size_t signatureLength) const;
2979 };
2980 
2981 /// \brief Interface for domains of simple key agreement protocols
2982 /// \details A key agreement domain is a set of parameters that must be shared
2983 /// by two parties in a key agreement protocol, along with the algorithms
2984 /// for generating key pairs and deriving agreed values.
2985 /// \since Crypto++ 3.0
2986 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
2987 {
2988 public:
2989  virtual ~SimpleKeyAgreementDomain() {}
2990 
2991  /// \brief Provides the size of the agreed value
2992  /// \return size of agreed value produced in this domain
2993  virtual unsigned int AgreedValueLength() const =0;
2994 
2995  /// \brief Provides the size of the private key
2996  /// \return size of private keys in this domain
2997  virtual unsigned int PrivateKeyLength() const =0;
2998 
2999  /// \brief Provides the size of the public key
3000  /// \return size of public keys in this domain
3001  virtual unsigned int PublicKeyLength() const =0;
3002 
3003  /// \brief Generate private key in this domain
3004  /// \param rng a RandomNumberGenerator derived class
3005  /// \param privateKey a byte buffer for the generated private key in this domain
3006  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3007  virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3008 
3009  /// \brief Generate a public key from a private key in this domain
3010  /// \param rng a RandomNumberGenerator derived class
3011  /// \param privateKey a byte buffer with the previously generated private key
3012  /// \param publicKey a byte buffer for the generated public key in this domain
3013  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
3014  virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3015 
3016  /// \brief Generate a private/public key pair
3017  /// \param rng a RandomNumberGenerator derived class
3018  /// \param privateKey a byte buffer for the generated private key in this domain
3019  /// \param publicKey a byte buffer for the generated public key in this domain
3020  /// \details GenerateKeyPair() is equivalent to calling GeneratePrivateKey() and then GeneratePublicKey().
3021  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3022  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
3023  virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3024 
3025  /// \brief Derive agreed value
3026  /// \param agreedValue a byte buffer for the shared secret
3027  /// \param privateKey a byte buffer with your private key in this domain
3028  /// \param otherPublicKey a byte buffer with the other party's public key in this domain
3029  /// \param validateOtherPublicKey a flag indicating if the other party's public key should be validated
3030  /// \return true upon success, false in case of failure
3031  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3032  /// \details The other party's public key is validated by default. If you have previously validated the
3033  /// static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3034  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3035  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3036  /// \pre <tt>COUNTOF(otherPublicKey) == PublicKeyLength()</tt>
3037  virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
3038 };
3039 
3040 /// \brief Interface for domains of authenticated key agreement protocols
3041 /// \details In an authenticated key agreement protocol, each party has two
3042 /// key pairs. The long-lived key pair is called the static key pair,
3043 /// and the short-lived key pair is called the ephemeral key pair.
3044 /// \since Crypto++ 3.0
3045 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3046 {
3047 public:
3048  virtual ~AuthenticatedKeyAgreementDomain() {}
3049 
3050  /// \brief Provides the size of the agreed value
3051  /// \return size of agreed value produced in this domain
3052  virtual unsigned int AgreedValueLength() const =0;
3053 
3054  /// \brief Provides the size of the static private key
3055  /// \return size of static private keys in this domain
3056  virtual unsigned int StaticPrivateKeyLength() const =0;
3057 
3058  /// \brief Provides the size of the static public key
3059  /// \return size of static public keys in this domain
3060  virtual unsigned int StaticPublicKeyLength() const =0;
3061 
3062  /// \brief Generate static private key in this domain
3063  /// \param rng a RandomNumberGenerator derived class
3064  /// \param privateKey a byte buffer for the generated private key in this domain
3065  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3066  virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3067 
3068  /// \brief Generate a static public key from a private key in this domain
3069  /// \param rng a RandomNumberGenerator derived class
3070  /// \param privateKey a byte buffer with the previously generated private key
3071  /// \param publicKey a byte buffer for the generated public key in this domain
3072  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3073  virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3074 
3075  /// \brief Generate a static private/public key pair
3076  /// \param rng a RandomNumberGenerator derived class
3077  /// \param privateKey a byte buffer for the generated private key in this domain
3078  /// \param publicKey a byte buffer for the generated public key in this domain
3079  /// \details GenerateStaticKeyPair() is equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey().
3080  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3081  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3082  virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3083 
3084  /// \brief Provides the size of ephemeral private key
3085  /// \return the size of ephemeral private key in this domain
3086  virtual unsigned int EphemeralPrivateKeyLength() const =0;
3087 
3088  /// \brief Provides the size of ephemeral public key
3089  /// \return the size of ephemeral public key in this domain
3090  virtual unsigned int EphemeralPublicKeyLength() const =0;
3091 
3092  /// \brief Generate ephemeral private key
3093  /// \param rng a RandomNumberGenerator derived class
3094  /// \param privateKey a byte buffer for the generated private key in this domain
3095  /// \pre <tt>COUNTOF(privateKey) == PrivateEphemeralKeyLength()</tt>
3096  virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3097 
3098  /// \brief Generate ephemeral public key
3099  /// \param rng a RandomNumberGenerator derived class
3100  /// \param privateKey a byte buffer for the generated private key in this domain
3101  /// \param publicKey a byte buffer for the generated public key in this domain
3102  /// \pre <tt>COUNTOF(publicKey) == PublicEphemeralKeyLength()</tt>
3103  virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3104 
3105  /// \brief Generate private/public key pair
3106  /// \param rng a RandomNumberGenerator derived class
3107  /// \param privateKey a byte buffer for the generated private key in this domain
3108  /// \param publicKey a byte buffer for the generated public key in this domain
3109  /// \details GenerateEphemeralKeyPair() is equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey()
3110  virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3111 
3112  /// \brief Derive agreed value
3113  /// \param agreedValue a byte buffer for the shared secret
3114  /// \param staticPrivateKey a byte buffer with your static private key in this domain
3115  /// \param ephemeralPrivateKey a byte buffer with your ephemeral private key in this domain
3116  /// \param staticOtherPublicKey a byte buffer with the other party's static public key in this domain
3117  /// \param ephemeralOtherPublicKey a byte buffer with the other party's ephemeral public key in this domain
3118  /// \param validateStaticOtherPublicKey a flag indicating if the other party's public key should be validated
3119  /// \return true upon success, false in case of failure
3120  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3121  /// \details The other party's ephemeral public key is validated by default. If you have previously validated
3122  /// the static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3123  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3124  /// \pre <tt>COUNTOF(staticPrivateKey) == StaticPrivateKeyLength()</tt>
3125  /// \pre <tt>COUNTOF(ephemeralPrivateKey) == EphemeralPrivateKeyLength()</tt>
3126  /// \pre <tt>COUNTOF(staticOtherPublicKey) == StaticPublicKeyLength()</tt>
3127  /// \pre <tt>COUNTOF(ephemeralOtherPublicKey) == EphemeralPublicKeyLength()</tt>
3128  virtual bool Agree(byte *agreedValue,
3129  const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
3130  const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
3131  bool validateStaticOtherPublicKey=true) const =0;
3132 };
3133 
3134 // interface for password authenticated key agreement protocols, not implemented yet
3135 #if 0
3136 /// \brief Interface for protocol sessions
3137 /*! The methods should be called in the following order:
3138 
3139  InitializeSession(rng, parameters); // or call initialize method in derived class
3140  while (true)
3141  {
3142  if (OutgoingMessageAvailable())
3143  {
3144  length = GetOutgoingMessageLength();
3145  GetOutgoingMessage(message);
3146  ; // send outgoing message
3147  }
3148 
3149  if (LastMessageProcessed())
3150  break;
3151 
3152  ; // receive incoming message
3153  ProcessIncomingMessage(message);
3154  }
3155  ; // call methods in derived class to obtain result of protocol session
3156 */
3157 class ProtocolSession
3158 {
3159 public:
3160  /// Exception thrown when an invalid protocol message is processed
3161  class ProtocolError : public Exception
3162  {
3163  public:
3164  ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
3165  };
3166 
3167  /// Exception thrown when a function is called unexpectedly
3168  /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
3169  class UnexpectedMethodCall : public Exception
3170  {
3171  public:
3172  UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
3173  };
3174 
3175  virtual ~ProtocolSession() {}
3176 
3177  ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {}
3178 
3179  virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
3180 
3181  bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
3182  void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
3183 
3184  bool HasValidState() const {return m_validState;}
3185 
3186  virtual bool OutgoingMessageAvailable() const =0;
3187  virtual unsigned int GetOutgoingMessageLength() const =0;
3188  virtual void GetOutgoingMessage(byte *message) =0;
3189 
3190  virtual bool LastMessageProcessed() const =0;
3191  virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
3192 
3193 protected:
3194  void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
3195  void CheckAndHandleInvalidState() const;
3196  void SetValidState(bool valid) {m_validState = valid;}
3197 
3198  RandomNumberGenerator *m_rng;
3199 
3200 private:
3201  bool m_throwOnProtocolError, m_validState;
3202 };
3203 
3204 class KeyAgreementSession : public ProtocolSession
3205 {
3206 public:
3207  virtual ~KeyAgreementSession() {}
3208 
3209  virtual unsigned int GetAgreedValueLength() const =0;
3210  virtual void GetAgreedValue(byte *agreedValue) const =0;
3211 };
3212 
3213 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
3214 {
3215 public:
3216  virtual ~PasswordAuthenticatedKeyAgreementSession() {}
3217 
3218  void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
3219  const byte *myId, unsigned int myIdLength,
3220  const byte *counterPartyId, unsigned int counterPartyIdLength,
3221  const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
3222 };
3223 
3224 /// \brief Password based key agreement domain
3225 /// \since Crypto++ 3.0
3226 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3227 {
3228 public:
3229  virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
3230 
3231  /// return whether the domain parameters stored in this object are valid
3232  virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
3233  {return GetCryptoParameters().Validate(rng, 2);}
3234 
3235  virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
3236  virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
3237 
3238  enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
3239 
3240  virtual bool IsValidRole(unsigned int role) =0;
3241  virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
3242 };
3243 #endif
3244 
3245 /// \brief Exception thrown when an ASN.1 BER decoing error is encountered
3246 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
3247 {
3248 public:
3249  BERDecodeErr() : InvalidArgument("BER decode error") {}
3250  BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
3251 };
3252 
3253 /// \brief Interface for encoding and decoding ASN1 objects
3254 /// \details Each class that derives from ASN1Object should provide a serialization format
3255 /// that controls subobject layout. Most of the time the serialization format is
3256 /// taken from a standard, like P1363 or an RFC.
3257 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
3258 {
3259 public:
3260  virtual ~ASN1Object() {}
3261 
3262  /// \brief Decode this object from a BufferedTransformation
3263  /// \param bt BufferedTransformation object
3264  /// \details Uses Basic Encoding Rules (BER)
3265  virtual void BERDecode(BufferedTransformation &bt) =0;
3266 
3267  /// \brief Encode this object into a BufferedTransformation
3268  /// \param bt BufferedTransformation object
3269  /// \details Uses Distinguished Encoding Rules (DER)
3270  virtual void DEREncode(BufferedTransformation &bt) const =0;
3271 
3272  /// \brief Encode this object into a BufferedTransformation
3273  /// \param bt BufferedTransformation object
3274  /// \details Uses Basic Encoding Rules (BER).
3275  /// \details This may be useful if DEREncode() would be too inefficient.
3276  virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
3277 };
3278 
3279 /// \brief Specifies the build-time version of the library
3280 /// \returns integer representing the build-time version
3281 /// \details LibraryVersion can help detect inadvertent mixing and matching of library
3282 /// versions. When using Crypto++ distributed by a third party, LibraryVersion()
3283 /// records the version of the shared object that was built by the third party.
3284 /// The LibraryVersion() record resides in <tt>cryptlib.o</tt> on Unix compatibles
3285 /// and <tt>cryptlib.obj</tt> on Windows. It does not change when an app links
3286 /// to the library.
3287 /// \details LibraryVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3288 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3289 /// the library version is 5.7 or above. If it is missing, then the library version is
3290 /// 5.6.5 or below.
3291 /// \details The function could be used as shown below.
3292 /// <pre>
3293 /// if (LibraryVersion() != HeaderVersion())
3294 /// {
3295 /// cout << "Potential version mismatch" << endl;
3296 ///
3297 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3298 /// const int lmin = (LibraryVersion() / 10U) % 10;
3299 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3300 /// const int hmin = (HeaderVersion() / 10U) % 10;
3301 ///
3302 /// if(lmaj != hmaj)
3303 /// cout << "Major version mismatch" << endl;
3304 /// else if(lmin != hmin)
3305 /// cout << "Minor version mismatch" << endl;
3306 /// }
3307 /// </pre>
3308 /// \sa HeaderVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3309 /// \since Crypto++ 6.0
3310 extern "C" {
3311  int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT);
3312 } // C linkage
3313 
3314 /// \brief Specifies the runtime version of the library
3315 /// \returns integer representing the runtime version
3316 /// \details HeaderVersion() can help detect inadvertent mixing and matching of library
3317 /// versions. When using Crypto++ distributed by a third party, HeaderVersion()
3318 /// records the version of the headers used by the app when the app is compiled.
3319 /// \details HeaderVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3320 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3321 /// the library version is 5.7 or above. If it is missing, then the library version is
3322 /// 5.6.5 or below.
3323 /// \details The function could be used as shown below.
3324 /// <pre>
3325 /// if (LibraryVersion() != HeaderVersion())
3326 /// {
3327 /// cout << "Potential version mismatch" << endl;
3328 ///
3329 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3330 /// const int lmin = (LibraryVersion() / 10U) % 10;
3331 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3332 /// const int hmin = (HeaderVersion() / 10U) % 10;
3333 ///
3334 /// if(lmaj != hmaj)
3335 /// cout << "Major version mismatch" << endl;
3336 /// else if(lmin != hmin)
3337 /// cout << "Minor version mismatch" << endl;
3338 /// }
3339 /// </pre>
3340 /// \sa LibraryVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3341 /// \since Crypto++ 6.0
3342 extern "C" {
3343 inline int HeaderVersion()
3344 {
3345  return CRYPTOPP_VERSION;
3346 }
3347 } // C linkage
3348 
3349 NAMESPACE_END
3350 
3351 #if CRYPTOPP_MSC_VERSION
3352 # pragma warning(pop)
3353 #endif
3354 
3355 #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:3343
Exception thrown when invalid crypto material is detected.
Definition: cryptlib.h:2367
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition: cryptlib.h:2446
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:1528
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:2533
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:2634
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:2401
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:2430
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition: cryptlib.h:2169
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:1796
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:2621
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:2850
Interface for public-key encryptors.
Definition: cryptlib.h:2671
virtual bool CanModifyInput() const
Determines whether input can be modified by the callee.
Definition: cryptlib.h:1706
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:2751
Flush(true) was called but it can&#39;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:2597
Interface for asymmetric algorithms using private keys.
Definition: cryptlib.h:2590
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
ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
Construct a ValueTypeMismatch.
Definition: cryptlib.h:336
virtual unsigned int NumberOfMessagesInThisSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:2083
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:1414
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:2585
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1864
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:1631
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:2514
virtual const BufferedTransformation * AttachedTransformation() const
Returns the object immediately attached to this object.
Definition: cryptlib.h:2321
Interface for cloning objects.
Definition: cryptlib.h:585
virtual size_t FixedCiphertextLength() const
Provides the fixed ciphertext length, if one exists.
Definition: cryptlib.h:2660
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:2002
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:400
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:1582
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:1715
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: cryptlib.h:2462
const std::type_info & GetRetrievingTypeInfo() const
Provides the retrieveing type.
Definition: cryptlib.h:346
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2467
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:2179
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:1723
Interface for domains of simple key agreement protocols.
Definition: cryptlib.h:2986
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2600
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:2157
Returns a decoding results.
Definition: cryptlib.h:277
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: cryptlib.h:2455
Exception thrown when trying to encrypt plaintext of invalid length.
Definition: cryptlib.h:2675
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:1964
Interface for public-key decryptors.
Definition: cryptlib.h:2706
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:2773
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1653
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.h:511
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:2838
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:3257
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:2189
DecodingResult()
Constructs a DecodingResult.
Definition: cryptlib.h:282
BufferedTransformation()
Construct a BufferedTransformation.
Definition: cryptlib.h:1637
Exception thrown when a filter does not recognize a named channel.
Definition: cryptlib.h:2160
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&#39;t be used.
Definition: cryptlib.h:2764
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:2086
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2315
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:1858
Interface for asymmetric algorithms using public keys.
Definition: cryptlib.h:2564
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:762
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:1435
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:2758
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:2330
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:1810
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:1663
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2834
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:2611
Exception thrown by objects that have not implemented nonblocking input processing.
Definition: cryptlib.h:1763
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:2573
void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
Transfer all bytes from this object to another BufferedTransformation.
Definition: cryptlib.h:2068
virtual const CryptoParameters & GetCryptoParameters() const
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2628
Interface for public-key signature verifiers.
Definition: cryptlib.h:2914
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:1490
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:1989
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.
Definition: cryptlib.h:2363
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1700
Interface for certificates.
Definition: cryptlib.h:2524
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2494
Interface for password based key derivation functions.
Definition: cryptlib.h:1566
CryptoMaterial & AccessMaterial()
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2618
An invalid argument was detected.
Definition: cryptlib.h:167
Interface for crypto material.
Definition: cryptlib.h:2483
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:1737
Interface for crypto prameters.
Definition: cryptlib.h:2519
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:40
bool isValidCoding
Flag to indicate the decoding is valid.
Definition: cryptlib.h:301
BufferedTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:1642
Namespace containing value name definitions.
Definition: argnames.h:13
BufferedTransformation received a Flush(true) signal but can&#39;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:1008
Interface for public keys.
Definition: cryptlib.h:2509
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:3045
virtual bool GetNextMessageSeries()
Retrieve the next message in a series.
Definition: cryptlib.h:2080
void TruncatedFinal(byte *digest, size_t digestSize)
Definition: cryptlib.h:2842
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:2046
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:3276
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:2413
virtual bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: cryptlib.h:2436
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:2239
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:1758
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:2607
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2577
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:2791
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:2309
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:2822
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: cryptlib.h:1427
InvalidCiphertext(const std::string &s)
Construct an InvalidCiphertext.
Definition: cryptlib.h:228
Interface for key derivation functions.
Definition: cryptlib.h:1502
virtual size_t FixedMaxPlaintextLength() const
Provides the maximum plaintext length given a fixed ciphertext length.
Definition: cryptlib.h:2667
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition: cryptlib.h:2227
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:3246
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