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  /// \return 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  /// \return 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> \c \#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
557 /// \c \#include <md5.h>
558 /// ...
559 /// CryptoPP::Weak::MD5 md5;
560 /// </pre>
561 DOCUMENTED_NAMESPACE_BEGIN(Weak)
562 // weak and wounded algorithms
563 DOCUMENTED_NAMESPACE_END
564 #endif
565 
566 /// \brief Namespace containing NaCl library functions
567 /// \details TweetNaCl is a compact and portable reimplementation of the NaCl library.
568 DOCUMENTED_NAMESPACE_BEGIN(NaCl)
569 // crypto_box, crypto_box_open, crypto_sign, and crypto_sign_open (and friends)
570 DOCUMENTED_NAMESPACE_END
571 
572 /// \brief Namespace containing testing and benchmark classes.
573 /// \details Source files for classes in the Test namespaces include
574 /// <tt>test.cpp</tt>, <tt>validat#.cpp</tt> and <tt>bench#.cpp</tt>.
575 DOCUMENTED_NAMESPACE_BEGIN(Test)
576 // testing and benchmark classes
577 DOCUMENTED_NAMESPACE_END
578 
579 // ********************************************************
580 
581 /// \brief Interface for cloning objects
582 /// \note this is \a not implemented by most classes
583 /// \sa ClonableImpl, NotCopyable
584 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
585 {
586 public:
587  virtual ~Clonable() {}
588 
589  /// \brief Copies this object
590  /// \return a copy of this object
591  /// \throws NotImplemented
592  /// \note this is \a not implemented by most classes
593  /// \sa NotCopyable
594  virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
595 };
596 
597 /// \brief Interface for all crypto algorithms
598 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
599 {
600 public:
601  virtual ~Algorithm() {}
602 
603  /// \brief Interface for all crypto algorithms
604  /// \param checkSelfTestStatus determines whether the object can proceed if the self
605  /// tests have not been run or failed.
606  /// \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
607  /// this constructor throws SelfTestFailure if the self test hasn't been run or fails.
608  /// \details FIPS 140-2 compliance is disabled by default. It is only used by certain
609  /// versions of the library when the library is built as a DLL on Windows. Also see
610  /// CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h.
611  Algorithm(bool checkSelfTestStatus = true);
612 
613  /// \brief Provides the name of this algorithm
614  /// \return the standard algorithm name
615  /// \details The standard algorithm name can be a name like <tt>AES</tt> or <tt>AES/GCM</tt>.
616  /// Some algorithms do not have standard names yet. For example, there is no standard
617  /// algorithm name for Shoup's ECIES.
618  /// \note AlgorithmName is not universally implemented yet.
619  virtual std::string AlgorithmName() const {return "unknown";}
620 
621  /// \brief Retrieve the provider of this algorithm
622  /// \return the algorithm provider
623  /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
624  /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
625  /// usually indicate a specialized implementation using instructions from a higher
626  /// instruction set architecture (ISA). Future labels may include external hardware
627  /// like a hardware security module (HSM).
628  /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
629  /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
630  /// instead of ASM.
631  /// \details Algorithms which combine different instructions or ISAs provide the
632  /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
633  /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
634  /// \note Provider is not universally implemented yet.
635  /// \since Crypto++ 8.0
636  virtual std::string AlgorithmProvider() const {return "C++";}
637 };
638 
639 /// \brief Interface for algorithms that take byte strings as keys
640 /// \sa FixedKeyLength(), VariableKeyLength(), SameKeyLengthAs(), SimpleKeyingInterfaceImpl()
641 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
642 {
643 public:
644  virtual ~SimpleKeyingInterface() {}
645 
646  /// \brief Returns smallest valid key length
647  /// \return the minimum key length, in bytes
648  virtual size_t MinKeyLength() const =0;
649 
650  /// \brief Returns largest valid key length
651  /// \return the maximum key length, in bytes
652  virtual size_t MaxKeyLength() const =0;
653 
654  /// \brief Returns default key length
655  /// \return the default key length, in bytes
656  virtual size_t DefaultKeyLength() const =0;
657 
658  /// \brief Returns a valid key length for the algorithm
659  /// \param keylength the size of the key, in bytes
660  /// \return the valid key length, in bytes
661  /// \details keylength is provided in bytes, not bits. If keylength is less than MIN_KEYLENGTH,
662  /// then the function returns MIN_KEYLENGTH. If keylength is greater than MAX_KEYLENGTH,
663  /// then the function returns MAX_KEYLENGTH. if If keylength is a multiple of KEYLENGTH_MULTIPLE,
664  /// then keylength is returned. Otherwise, the function returns a \a lower multiple of
665  /// KEYLENGTH_MULTIPLE.
666  virtual size_t GetValidKeyLength(size_t keylength) const =0;
667 
668  /// \brief Returns whether keylength is a valid key length
669  /// \param keylength the requested keylength
670  /// \return true if keylength is valid, false otherwise
671  /// \details Internally the function calls GetValidKeyLength()
672  virtual bool IsValidKeyLength(size_t keylength) const
673  {return keylength == GetValidKeyLength(keylength);}
674 
675  /// \brief Sets or reset the key of this object
676  /// \param key the key to use when keying the object
677  /// \param length the size of the key, in bytes
678  /// \param params additional initialization parameters to configure this object
679  virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
680 
681  /// \brief Sets or reset the key of this object
682  /// \param key the key to use when keying the object
683  /// \param length the size of the key, in bytes
684  /// \param rounds the number of rounds to apply the transformation function,
685  /// if applicable
686  /// \details SetKeyWithRounds() calls SetKey() with a NameValuePairs
687  /// object that only specifies rounds. rounds is an integer parameter,
688  /// and <tt>-1</tt> means use the default number of rounds.
689  void SetKeyWithRounds(const byte *key, size_t length, int rounds);
690 
691  /// \brief Sets or reset the key of this object
692  /// \param key the key to use when keying the object
693  /// \param length the size of the key, in bytes
694  /// \param iv the initialization vector to use when keying the object
695  /// \param ivLength the size of the iv, in bytes
696  /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs
697  /// that only specifies IV. The IV is a byte buffer with size ivLength.
698  /// ivLength is an integer parameter, and <tt>-1</tt> means use IVSize().
699  void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
700 
701  /// \brief Sets or reset the key of this object
702  /// \param key the key to use when keying the object
703  /// \param length the size of the key, in bytes
704  /// \param iv the initialization vector to use when keying the object
705  /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs() object
706  /// that only specifies iv. iv is a byte buffer, and it must have
707  /// a size IVSize().
708  void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
709  {SetKeyWithIV(key, length, iv, IVSize());}
710 
711  /// \brief Secure IVs requirements as enumerated values.
712  /// \details Provides secure IV requirements as a monotonically increasing enumerated values.
713  /// Requirements can be compared using less than (&lt;) and greater than (&gt;). For example,
714  /// <tt>UNIQUE_IV &lt; RANDOM_IV</tt> and <tt>UNPREDICTABLE_RANDOM_IV &gt; RANDOM_IV</tt>.
715  /// \details Objects that use SimpleKeyingInterface do not support an optional IV. That is,
716  /// an IV must be present or it must be absent. If you wish to support an optional IV then
717  /// provide two classes - one with an IV and one without an IV.
718  /// \sa IsResynchronizable(), CanUseRandomIVs(), CanUsePredictableIVs(), CanUseStructuredIVs()
720  /// \brief The IV must be unique
721  UNIQUE_IV = 0,
722  /// \brief The IV must be random and possibly predictable
724  /// \brief The IV must be random and unpredictable
726  /// \brief The IV is set by the object
728  /// \brief The object does not use an IV
729  NOT_RESYNCHRONIZABLE
730  };
731 
732  /// \brief Minimal requirement for secure IVs
733  /// \return the secure IV requirement of the algorithm
734  virtual IV_Requirement IVRequirement() const =0;
735 
736  /// \brief Determines if the object can be resynchronized
737  /// \return true if the object can be resynchronized (i.e. supports initialization vectors), false otherwise
738  /// \note If this function returns true, and no IV is passed to SetKey() and <tt>CanUseStructuredIVs()==true</tt>,
739  /// an IV of all 0's will be assumed.
740  bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
741 
742  /// \brief Determines if the object can use random IVs
743  /// \return true if the object can use random IVs (in addition to ones returned by GetNextIV), false otherwise
744  bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
745 
746  /// \brief Determines if the object can use random but possibly predictable IVs
747  /// \return true if the object can use random but possibly predictable IVs (in addition to ones returned by
748  /// GetNextIV), false otherwise
749  bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
750 
751  /// \brief Determines if the object can use structured IVs
752  /// \return true if the object can use structured IVs, false otherwise
753  /// \details CanUseStructuredIVs() indicates whether the object can use structured IVs; for example a counter
754  /// (in addition to ones returned by GetNextIV).
755  bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
756 
757  /// \brief Returns length of the IV accepted by this object
758  /// \return the size of an IV, in bytes
759  /// \throws NotImplemented() if the object does not support resynchronization
760  /// \details The default implementation throws NotImplemented
761  virtual unsigned int IVSize() const
762  {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
763 
764  /// \brief Provides the default size of an IV
765  /// \return default length of IVs accepted by this object, in bytes
766  unsigned int DefaultIVLength() const {return IVSize();}
767 
768  /// \brief Provides the minimum size of an IV
769  /// \return minimal length of IVs accepted by this object, in bytes
770  /// \throws NotImplemented() if the object does not support resynchronization
771  virtual unsigned int MinIVLength() const {return IVSize();}
772 
773  /// \brief Provides the maximum size of an IV
774  /// \return maximal length of IVs accepted by this object, in bytes
775  /// \throws NotImplemented() if the object does not support resynchronization
776  virtual unsigned int MaxIVLength() const {return IVSize();}
777 
778  /// \brief Resynchronize with an IV
779  /// \param iv the initialization vector
780  /// \param ivLength the size of the initialization vector, in bytes
781  /// \details Resynchronize() resynchronizes with an IV provided by the caller. <tt>ivLength=-1</tt> means use IVSize().
782  /// \throws NotImplemented() if the object does not support resynchronization
783  virtual void Resynchronize(const byte *iv, int ivLength=-1) {
784  CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength);
785  throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");
786  }
787 
788  /// \brief Retrieves a secure IV for the next message
789  /// \param rng a RandomNumberGenerator to produce keying material
790  /// \param iv a block of bytes to receive the IV
791  /// \details The IV must be at least IVSize() in length.
792  /// \details This method should be called after you finish encrypting one message and are ready
793  /// to start the next one. After calling it, you must call SetKey() or Resynchronize().
794  /// before using this object again.
795  /// \details Internally, the base class implementation calls RandomNumberGenerator's GenerateBlock()
796  /// \note This method is not implemented on decryption objects.
797  virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
798 
799 protected:
800  /// \brief Returns the base class Algorithm
801  /// \return the base class Algorithm
802  virtual const Algorithm & GetAlgorithm() const =0;
803 
804  /// \brief Sets the key for this object without performing parameter validation
805  /// \param key a byte buffer used to key the cipher
806  /// \param length the length of the byte buffer
807  /// \param params additional parameters passed as NameValuePairs
808  /// \details key must be at least DEFAULT_KEYLENGTH in length.
809  virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
810 
811  /// \brief Validates the key length
812  /// \param length the size of the keying material, in bytes
813  /// \throws InvalidKeyLength if the key length is invalid
814  void ThrowIfInvalidKeyLength(size_t length);
815 
816  /// \brief Validates the object
817  /// \throws InvalidArgument if the IV is present
818  /// \details Internally, the default implementation calls IsResynchronizable() and throws
819  /// InvalidArgument if the function returns true.
820  /// \note called when no IV is passed
821  void ThrowIfResynchronizable();
822 
823  /// \brief Validates the IV
824  /// \param iv the IV with a length of IVSize, in bytes
825  /// \throws InvalidArgument on failure
826  /// \details Internally, the default implementation checks the iv. If iv is not NULL or nullptr,
827  /// then the function succeeds. If iv is NULL, then IVRequirement is checked against
828  /// UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then
829  /// then the function succeeds. Otherwise, an exception is thrown.
830  void ThrowIfInvalidIV(const byte *iv);
831 
832  /// \brief Validates the IV length
833  /// \param length the size of an IV, in bytes
834  /// \throws InvalidArgument if the IV length is invalid
835  size_t ThrowIfInvalidIVLength(int length);
836 
837  /// \brief Retrieves and validates the IV
838  /// \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter
839  /// \param size the length of the IV, in bytes
840  /// \return a pointer to the first byte of the IV
841  /// \throws InvalidArgument if the number of rounds are invalid
842  const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
843 
844  /// \brief Validates the key length
845  /// \param length the size of the keying material, in bytes
846  inline void AssertValidKeyLength(size_t length) const
847  {CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));}
848 };
849 
850 /// \brief Interface for the data processing part of block ciphers
851 /// \details Classes derived from BlockTransformation are block ciphers
852 /// in ECB mode (for example the DES::Encryption class), which are stateless.
853 /// These classes should not be used directly, but only in combination with
854 /// a mode class (see CipherModeDocumentation in modes.h).
855 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
856 {
857 public:
858  virtual ~BlockTransformation() {}
859 
860  /// \brief Encrypt or decrypt a block
861  /// \param inBlock the input message before processing
862  /// \param outBlock the output message after processing
863  /// \param xorBlock an optional XOR mask
864  /// \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock.
865  /// \details The size of the block is determined by the block cipher and its documentation. Use
866  /// BLOCKSIZE at compile time, or BlockSize() at runtime.
867  /// \note The message can be transformed in-place, or the buffers must \a not overlap
868  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
869  virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
870 
871  /// \brief Encrypt or decrypt a block
872  /// \param inBlock the input message before processing
873  /// \param outBlock the output message after processing
874  /// \details ProcessBlock encrypts or decrypts inBlock and write to outBlock.
875  /// \details The size of the block is determined by the block cipher and its documentation.
876  /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
877  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
878  /// \note The message can be transformed in-place, or the buffers must \a not overlap
879  void ProcessBlock(const byte *inBlock, byte *outBlock) const
880  {ProcessAndXorBlock(inBlock, NULLPTR, outBlock);}
881 
882  /// \brief Encrypt or decrypt a block in place
883  /// \param inoutBlock the input message before processing
884  /// \details ProcessBlock encrypts or decrypts inoutBlock in-place.
885  /// \details The size of the block is determined by the block cipher and its documentation.
886  /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
887  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
888  void ProcessBlock(byte *inoutBlock) const
889  {ProcessAndXorBlock(inoutBlock, NULLPTR, inoutBlock);}
890 
891  /// Provides the block size of the cipher
892  /// \return the block size of the cipher, in bytes
893  virtual unsigned int BlockSize() const =0;
894 
895  /// \brief Provides input and output data alignment for optimal performance.
896  /// \return the input data alignment that provides optimal performance
897  /// \sa GetAlignment() and OptimalBlockSize()
898  virtual unsigned int OptimalDataAlignment() const;
899 
900  /// \brief Determines if the transformation is a permutation
901  /// \return true if this is a permutation (i.e. there is an inverse transformation)
902  virtual bool IsPermutation() const {return true;}
903 
904  /// \brief Determines if the cipher is being operated in its forward direction
905  /// \return true if DIR is ENCRYPTION, false otherwise
906  /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
907  virtual bool IsForwardTransformation() const =0;
908 
909  /// \brief Determines the number of blocks that can be processed in parallel
910  /// \return the number of blocks that can be processed in parallel, for bit-slicing implementations
911  /// \details Bit-slicing is often used to improve throughput and minimize timing attacks.
912  virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
913 
914  /// \brief Bit flags that control AdvancedProcessBlocks() behavior
916  /// \brief inBlock is a counter
917  BT_InBlockIsCounter=1,
918  /// \brief should not modify block pointers
919  BT_DontIncrementInOutPointers=2,
920  /// \brief Xor inputs before transformation
921  BT_XorInput=4,
922  /// \brief perform the transformation in reverse
923  BT_ReverseDirection=8,
924  /// \brief Allow parallel transformations
925  BT_AllowParallel=16};
926 
927  /// \brief Encrypt and xor multiple blocks using additional flags
928  /// \param inBlocks the input message before processing
929  /// \param xorBlocks an optional XOR mask
930  /// \param outBlocks the output message after processing
931  /// \param length the size of the blocks, in bytes
932  /// \param flags additional flags to control processing
933  /// \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags.
934  /// \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified.
935  virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
936 
937  /// \brief Provides the direction of the cipher
938  /// \return ENCRYPTION if IsForwardTransformation() is true, DECRYPTION otherwise
939  /// \sa IsForwardTransformation(), IsPermutation()
940  inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
941 };
942 
943 /// \brief Interface for the data processing portion of stream ciphers
944 /// \sa StreamTransformationFilter()
945 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
946 {
947 public:
948  virtual ~StreamTransformation() {}
949 
950  /// \brief Provides a reference to this object
951  /// \return A reference to this object
952  /// \details Useful for passing a temporary object to a function that takes a non-const reference
953  StreamTransformation& Ref() {return *this;}
954 
955  /// \brief Provides the mandatory block size of the cipher
956  /// \return The block size of the cipher if input must be processed in blocks, 1 otherwise
957  /// \details Stream ciphers and some block ciphers modes of operation return 1. Modes that
958  /// return 1 must be able to process a single byte at a time, like counter mode. If a
959  /// mode of operation or block cipher cannot stream then it must not return 1.
960  /// \details When filters operate the mode or cipher, ProcessData will be called with a
961  /// string of bytes that is determined by MandatoryBlockSize and OptimalBlockSize. When a
962  /// policy is set, like 16-byte strings for a 16-byte block cipher, the filter will buffer
963  /// bytes until the specified number of bytes is available to the object.
964  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
965  virtual unsigned int MandatoryBlockSize() const {return 1;}
966 
967  /// \brief Provides the input block size most efficient for this cipher
968  /// \return The input block size that is most efficient for the cipher
969  /// \details The base class implementation returns MandatoryBlockSize().
970  /// \note Optimal input length is
971  /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>.
972  virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
973 
974  /// \brief Provides the number of bytes used in the current block when processing at optimal block size.
975  /// \return the number of bytes used in the current block when processing at the optimal block size
976  virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
977 
978  /// \brief Provides input and output data alignment for optimal performance
979  /// \return the input data alignment that provides optimal performance
980  /// \sa GetAlignment() and OptimalBlockSize()
981  virtual unsigned int OptimalDataAlignment() const;
982 
983  /// \brief Encrypt or decrypt an array of bytes
984  /// \param outString the output byte buffer
985  /// \param inString the input byte buffer
986  /// \param length the size of the input and output byte buffers, in bytes
987  /// \details ProcessData is called with a string of bytes whose size depends on MandatoryBlockSize.
988  /// Either <tt>inString == outString</tt>, or they must not overlap.
989  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
990  virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
991 
992  /// \brief Encrypt or decrypt the last block of data
993  /// \param outString the output byte buffer
994  /// \param outLength the size of the output byte buffer, in bytes
995  /// \param inString the input byte buffer
996  /// \param inLength the size of the input byte buffer, in bytes
997  /// \return the number of bytes used in outString
998  /// \details ProcessLastBlock is used when the last block of data is special and requires handling
999  /// by the cipher. The current implementation provides an output buffer with a size
1000  /// <tt>inLength+2*MandatoryBlockSize()</tt>. The return value allows the cipher to expand cipher
1001  /// text during encryption or shrink plain text during decryption.
1002  /// \details This member function is used by CBC-CTS and OCB modes.
1003  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
1004  virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
1005 
1006  /// \brief Provides the size of the last block
1007  /// \return the minimum size of the last block
1008  /// \details MinLastBlockSize() returns the minimum size of the last block. 0 indicates the last
1009  /// block is not special.
1010  /// \details MandatoryBlockSize() enlists one of two behaviors. First, if MandatoryBlockSize()
1011  /// returns 1, then the cipher can be streamed and ProcessData() is called with the tail bytes.
1012  /// Second, if MandatoryBlockSize() returns non-0, then the string of bytes is padded to
1013  /// MandatoryBlockSize() according to the padding mode. Then, ProcessData() is called with the
1014  /// padded string of bytes.
1015  /// \details Some authenticated encryption modes are not expressed well with MandatoryBlockSize()
1016  /// and MinLastBlockSize(). For example, AES/OCB uses 16-byte blocks (MandatoryBlockSize = 16)
1017  /// and the last block requires special processing (MinLastBlockSize = 0). However, 0 is a valid
1018  /// last block size for OCB and the special processing is custom padding, and not standard PKCS
1019  /// padding. In response an unambiguous IsLastBlockSpecial() was added.
1020  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
1021  virtual unsigned int MinLastBlockSize() const {return 0;}
1022 
1023  /// \brief Determines if the last block receives special processing
1024  /// \return true if the last block reveives special processing, false otherwise.
1025  /// \details Some authenticated encryption modes are not expressed well with
1026  /// MandatoryBlockSize() and MinLastBlockSize(). For example, AES/OCB uses
1027  /// 16-byte blocks (MandatoryBlockSize = 16) and the last block requires special processing
1028  /// (MinLastBlockSize = 0). However, 0 is a valid last block size for OCB and the special
1029  /// processing is custom padding, and not standard PKCS padding. In response an
1030  /// unambiguous IsLastBlockSpecial() was added.
1031  /// \details When IsLastBlockSpecial() returns false nothing special happens. All the former
1032  /// rules and behaviors apply. This is the default behavior of IsLastBlockSpecial().
1033  /// \details When IsLastBlockSpecial() returns true four things happen. First, MinLastBlockSize = 0
1034  /// means 0 is a valid block size that should be processed. Second, standard block cipher padding is
1035  /// \a not \a applied. Third, the caller supplies an outString is larger than inString by
1036  /// <tt>2*MandatoryBlockSize()</tt>. That is, there's a reserve available when processing the last block.
1037  /// Fourth, the cipher is responsible for finalization like custom padding. The cipher will tell
1038  /// the library how many bytes were processed or used by returning the appropriate value from
1039  /// ProcessLastBlock().
1040  /// \details The return value of ProcessLastBlock() indicates how many bytes were written to
1041  /// <tt>outString</tt>. A filter pipelining data will send <tt>outString</tt> and up to <tt>outLength</tt>
1042  /// to an <tt>AttachedTransformation()</tt> for additional processing. Below is an example of the code
1043  /// used in <tt>StreamTransformationFilter::LastPut</tt>.
1044  /// <pre> if (m_cipher.IsLastBlockSpecial())
1045  /// {
1046  /// size_t reserve = 2*m_cipher.MandatoryBlockSize();
1047  /// space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, length+reserve);
1048  /// length = m_cipher.ProcessLastBlock(space, length+reserve, inString, length);
1049  /// AttachedTransformation()->Put(space, length);
1050  /// return;
1051  /// }</pre>
1052  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
1053  /// \since Crypto++ 6.0
1054  virtual bool IsLastBlockSpecial() const {return false;}
1055 
1056  /// \brief Encrypt or decrypt a string of bytes
1057  /// \param inoutString the string to process
1058  /// \param length the size of the inoutString, in bytes
1059  /// \details Internally, the base class implementation calls ProcessData().
1060  inline void ProcessString(byte *inoutString, size_t length)
1061  {ProcessData(inoutString, inoutString, length);}
1062 
1063  /// \brief Encrypt or decrypt a string of bytes
1064  /// \param outString the output string to process
1065  /// \param inString the input string to process
1066  /// \param length the size of the input and output strings, in bytes
1067  /// \details Internally, the base class implementation calls ProcessData().
1068  inline void ProcessString(byte *outString, const byte *inString, size_t length)
1069  {ProcessData(outString, inString, length);}
1070 
1071  /// \brief Encrypt or decrypt a byte
1072  /// \param input the input byte to process
1073  /// \details Internally, the base class implementation calls ProcessData() with a size of 1.
1074  inline byte ProcessByte(byte input)
1075  {ProcessData(&input, &input, 1); return input;}
1076 
1077  /// \brief Determines whether the cipher supports random access
1078  /// \return true if the cipher supports random access, false otherwise
1079  virtual bool IsRandomAccess() const =0;
1080 
1081  /// \brief Seek to an absolute position
1082  /// \param pos position to seek
1083  /// \throws NotImplemented
1084  /// \details The base class implementation throws NotImplemented. The function
1085  /// \ref CRYPTOPP_ASSERT "asserts" IsRandomAccess() in debug builds.
1086  virtual void Seek(lword pos)
1087  {
1088  CRYPTOPP_UNUSED(pos);
1089  CRYPTOPP_ASSERT(!IsRandomAccess());
1090  throw NotImplemented("StreamTransformation: this object doesn't support random access");
1091  }
1092 
1093  /// \brief Determines whether the cipher is self-inverting
1094  /// \return true if the cipher is self-inverting, false otherwise
1095  /// \details IsSelfInverting determines whether this transformation is
1096  /// self-inverting (e.g. xor with a keystream).
1097  virtual bool IsSelfInverting() const =0;
1098 
1099  /// \brief Determines if the cipher is being operated in its forward direction
1100  /// \return true if DIR is ENCRYPTION, false otherwise
1101  /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
1102  virtual bool IsForwardTransformation() const =0;
1103 };
1104 
1105 /// \brief Interface for hash functions and data processing part of MACs
1106 /// \details HashTransformation objects are stateful. They are created in an initial state,
1107 /// change state as Update() is called, and return to the initial
1108 /// state when Final() is called. This interface allows a large message to
1109 /// be hashed in pieces by calling Update() on each piece followed by
1110 /// calling Final().
1111 /// \sa HashFilter(), HashVerificationFilter()
1112 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
1113 {
1114 public:
1115  virtual ~HashTransformation() {}
1116 
1117  /// \brief Provides a reference to this object
1118  /// \return A reference to this object
1119  /// \details Useful for passing a temporary object to a function that takes a non-const reference
1120  HashTransformation& Ref() {return *this;}
1121 
1122  /// \brief Updates a hash with additional input
1123  /// \param input the additional input as a buffer
1124  /// \param length the size of the buffer, in bytes
1125  virtual void Update(const byte *input, size_t length) =0;
1126 
1127  /// \brief Request space which can be written into by the caller
1128  /// \param size the requested size of the buffer
1129  /// \details The purpose of this method is to help avoid extra memory allocations.
1130  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1131  /// size is the requested size of the buffer. When the call returns, size is the size of
1132  /// the array returned to the caller.
1133  /// \details The base class implementation sets size to 0 and returns NULL or nullptr.
1134  /// \note Some objects, like ArraySink, cannot create a space because its fixed.
1135  virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULLPTR;}
1136 
1137  /// \brief Computes the hash of the current message
1138  /// \param digest a pointer to the buffer to receive the hash
1139  /// \details Final() restarts the hash for a new message.
1140  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1141  /// the output byte buffer is large enough for the digest.
1142  virtual void Final(byte *digest)
1143  {TruncatedFinal(digest, DigestSize());}
1144 
1145  /// \brief Restart the hash
1146  /// \details Discards the current state, and restart for a new message
1147  virtual void Restart()
1148  {TruncatedFinal(NULLPTR, 0);}
1149 
1150  /// Provides the digest size of the hash
1151  /// \return the digest size of the hash.
1152  virtual unsigned int DigestSize() const =0;
1153 
1154  /// Provides the tag size of the hash
1155  /// \return the tag size of the hash.
1156  /// \details Same as DigestSize().
1157  unsigned int TagSize() const {return DigestSize();}
1158 
1159  /// \brief Provides the block size of the compression function
1160  /// \return block size of the compression function, in bytes
1161  /// \details BlockSize() will return 0 if the hash is not block based
1162  /// or does not have an equivalent block size. For example, Keccak
1163  /// and SHA-3 do not have a block size, but they do have an equivalent
1164  /// block size called rate expressed as <tt>r</tt>.
1165  virtual unsigned int BlockSize() const {return 0;}
1166 
1167  /// \brief Provides the input block size most efficient for this hash.
1168  /// \return The input block size that is most efficient for the cipher
1169  /// \details The base class implementation returns MandatoryBlockSize().
1170  /// \details Optimal input length is
1171  /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>.
1172  virtual unsigned int OptimalBlockSize() const {return 1;}
1173 
1174  /// \brief Provides input and output data alignment for optimal performance
1175  /// \return the input data alignment that provides optimal performance
1176  /// \sa GetAlignment() and OptimalBlockSize()
1177  virtual unsigned int OptimalDataAlignment() const;
1178 
1179  /// \brief Updates the hash with additional input and computes the hash of the current message
1180  /// \param digest a pointer to the buffer to receive the hash
1181  /// \param input the additional input as a buffer
1182  /// \param length the size of the buffer, in bytes
1183  /// \details Use this if your input is in one piece and you don't want to call Update()
1184  /// and Final() separately
1185  /// \details CalculateDigest() restarts the hash for the next message.
1186  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1187  /// the output byte buffer is large enough for the digest.
1188  virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
1189  {Update(input, length); Final(digest);}
1190 
1191  /// \brief Verifies the hash of the current message
1192  /// \param digest a pointer to the buffer of an \a existing hash
1193  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1194  /// \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
1195  /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
1196  /// a constant time comparison function. digestLength cannot exceed DigestSize().
1197  /// \details Verify() restarts the hash for the next message.
1198  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1199  /// the output byte buffer is large enough for the digest.
1200  virtual bool Verify(const byte *digest)
1201  {return TruncatedVerify(digest, DigestSize());}
1202 
1203  /// \brief Updates the hash with additional input and verifies the hash of the current message
1204  /// \param digest a pointer to the buffer of an \a existing hash
1205  /// \param input the additional input as a buffer
1206  /// \param length the size of the buffer, in bytes
1207  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1208  /// \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
1209  /// \details Use this if your input is in one piece and you don't want to call Update()
1210  /// and Verify() separately
1211  /// \details VerifyDigest() performs a bitwise compare on the buffers using VerifyBufsEqual(),
1212  /// which is a constant time comparison function. digestLength cannot exceed DigestSize().
1213  /// \details VerifyDigest() restarts the hash for the next message.
1214  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1215  /// the output byte buffer is large enough for the digest.
1216  virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
1217  {Update(input, length); return Verify(digest);}
1218 
1219  /// \brief Computes the hash of the current message
1220  /// \param digest a pointer to the buffer to receive the hash
1221  /// \param digestSize the size of the truncated digest, in bytes
1222  /// \details TruncatedFinal() call Final() and then copies digestSize bytes to digest.
1223  /// The hash is restarted the hash for the next message.
1224  virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
1225 
1226  /// \brief Updates the hash with additional input and computes the hash of the current message
1227  /// \param digest a pointer to the buffer to receive the hash
1228  /// \param digestSize the length of the truncated hash, in bytes
1229  /// \param input the additional input as a buffer
1230  /// \param length the size of the buffer, in bytes
1231  /// \details Use this if your input is in one piece and you don't want to call Update()
1232  /// and CalculateDigest() separately.
1233  /// \details CalculateTruncatedDigest() restarts the hash for the next message.
1234  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1235  /// the output byte buffer is large enough for the digest.
1236  virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
1237  {Update(input, length); TruncatedFinal(digest, digestSize);}
1238 
1239  /// \brief Verifies the hash of the current message
1240  /// \param digest a pointer to the buffer of an \a existing hash
1241  /// \param digestLength the size of the truncated hash, in bytes
1242  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1243  /// \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
1244  /// \details TruncatedVerify() is a truncated version of Verify(). It can operate on a
1245  /// buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
1246  /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
1247  /// a constant time comparison function. digestLength cannot exceed DigestSize().
1248  /// \details TruncatedVerify() restarts the hash for the next message.
1249  virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
1250 
1251  /// \brief Updates the hash with additional input and verifies the hash of the current message
1252  /// \param digest a pointer to the buffer of an \a existing hash
1253  /// \param digestLength the size of the truncated hash, in bytes
1254  /// \param input the additional input as a buffer
1255  /// \param length the size of the buffer, in bytes
1256  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1257  /// \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
1258  /// \details Use this if your input is in one piece and you don't want to call Update()
1259  /// and TruncatedVerify() separately.
1260  /// \details VerifyTruncatedDigest() is a truncated version of VerifyDigest(). It can operate
1261  /// on a buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
1262  /// \details VerifyTruncatedDigest() restarts the hash for the next message.
1263  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1264  /// the output byte buffer is large enough for the digest.
1265  virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
1266  {Update(input, length); return TruncatedVerify(digest, digestLength);}
1267 
1268 protected:
1269  /// \brief Validates a truncated digest size
1270  /// \param size the requested digest size
1271  /// \throws InvalidArgument if the algorithm's digest size cannot be truncated to the requested size
1272  /// \details Throws an exception when the truncated digest size is greater than DigestSize()
1273  void ThrowIfInvalidTruncatedSize(size_t size) const;
1274 };
1275 
1276 /// \brief Interface for one direction (encryption or decryption) of a block cipher
1277 /// \details These objects usually should not be used directly. See BlockTransformation for more details.
1278 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
1279 {
1280 protected:
1281  const Algorithm & GetAlgorithm() const {return *this;}
1282 };
1283 
1284 /// \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode
1285 /// \details These objects usually should not be used directly. See StreamTransformation for more details.
1286 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
1287 {
1288 protected:
1289  const Algorithm & GetAlgorithm() const {return *this;}
1290 };
1291 
1292 /// \brief Interface for message authentication codes
1293 /// \details These objects usually should not be used directly. See HashTransformation for more details.
1294 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
1295 {
1296 protected:
1297  const Algorithm & GetAlgorithm() const {return *this;}
1298 };
1299 
1300 /// \brief Interface for authenticated encryption modes of operation
1301 /// \details AuthenticatedSymmetricCipher() provides the interface for one direction
1302 /// (encryption or decryption) of a stream cipher or block cipher mode with authentication. The
1303 /// StreamTransformation() part of this interface is used to encrypt or decrypt the data. The
1304 /// MessageAuthenticationCode() part of the interface is used to input additional authenticated
1305 /// data (AAD), which is MAC'ed but not encrypted. The MessageAuthenticationCode() part is also
1306 /// used to generate and verify the MAC.
1307 /// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
1308 /// and OCB mode. All modes implement AuthenticatedSymmetricCipher() and the motivation for
1309 /// the API, like calling AAD a &quot;header&quot;, can be found in Bellare, Rogaway and
1310 /// Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX Mode of
1311 /// Operation</A>. The EAX paper suggested a basic API to help standardize AEAD schemes in
1312 /// software and promote adoption of the modes.
1313 /// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
1314 /// Encryption</A> on the Crypto++ wiki.
1315 /// \since Crypto++ 5.6.0
1316 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
1317 {
1318 public:
1319  virtual ~AuthenticatedSymmetricCipher() {}
1320 
1321  /// \brief Exception thrown when the object is in the wrong state for the operation
1322  /// \details this indicates that a member function was called in the wrong state, for example trying to encrypt
1323  /// a message before having set the key or IV
1324  class BadState : public Exception
1325  {
1326  public:
1327  explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
1328  explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
1329  };
1330 
1331  /// \brief Provides the maximum length of AAD that can be input
1332  /// \return the maximum length of AAD that can be input before the encrypted data
1333  virtual lword MaxHeaderLength() const =0;
1334 
1335  /// \brief Provides the maximum length of encrypted data
1336  /// \return the maximum length of encrypted data
1337  virtual lword MaxMessageLength() const =0;
1338 
1339  /// \brief Provides the the maximum length of AAD
1340  /// \return the maximum length of AAD that can be input after the encrypted data
1341  virtual lword MaxFooterLength() const {return 0;}
1342 
1343  /// \brief Determines if data lengths must be specified prior to inputting data
1344  /// \return true if the data lengths are required before inputting data, false otherwise
1345  /// \details if this function returns true, SpecifyDataLengths() must be called before attempting to input data.
1346  /// This is the case for some schemes, such as CCM.
1347  /// \sa SpecifyDataLengths()
1348  virtual bool NeedsPrespecifiedDataLengths() const {return false;}
1349 
1350  /// \brief Prescribes the data lengths
1351  /// \param headerLength size of data before message is input, in bytes
1352  /// \param messageLength size of the message, in bytes
1353  /// \param footerLength size of data after message is input, in bytes
1354  /// \details SpecifyDataLengths() only needs to be called if NeedsPrespecifiedDataLengths() returns <tt>true</tt>.
1355  /// If <tt>true</tt>, then <tt>headerLength</tt> will be validated against <tt>MaxHeaderLength()</tt>,
1356  /// <tt>messageLength</tt> will be validated against <tt>MaxMessageLength()</tt>, and
1357  /// <tt>footerLength</tt> will be validated against <tt>MaxFooterLength()</tt>.
1358  /// \sa NeedsPrespecifiedDataLengths()
1359  void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
1360 
1361  /// \brief Encrypts and calculates a MAC in one call
1362  /// \param ciphertext the encryption buffer
1363  /// \param mac the mac buffer
1364  /// \param macSize the size of the MAC buffer, in bytes
1365  /// \param iv the iv buffer
1366  /// \param ivLength the size of the IV buffer, in bytes
1367  /// \param header the AAD buffer
1368  /// \param headerLength the size of the AAD buffer, in bytes
1369  /// \param message the message buffer
1370  /// \param messageLength the size of the messagetext buffer, in bytes
1371  /// \details EncryptAndAuthenticate() encrypts and generates the MAC in one call. The function
1372  /// truncates the MAC if <tt>macSize < TagSize()</tt>.
1373  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);
1374 
1375  /// \brief Decrypts and verifies a MAC in one call
1376  /// \param message the decryption buffer
1377  /// \param mac the mac buffer
1378  /// \param macSize the size of the MAC buffer, in bytes
1379  /// \param iv the iv buffer
1380  /// \param ivLength the size of the IV buffer, in bytes
1381  /// \param header the AAD buffer
1382  /// \param headerLength the size of the AAD buffer, in bytes
1383  /// \param ciphertext the ciphertext buffer
1384  /// \param ciphertextLength the size of the ciphertext buffer, in bytes
1385  /// \return true if the MAC is valid and the decoding succeeded, false otherwise
1386  /// \details DecryptAndVerify() decrypts and verifies the MAC in one call.
1387  /// <tt>message</tt> is a decryption buffer and should be at least as large as the ciphertext buffer.
1388  /// \details The function returns true iff MAC is valid. DecryptAndVerify() assumes the MAC
1389  /// is truncated if <tt>macLength < TagSize()</tt>.
1390  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);
1391 
1392  /// \brief Provides the name of this algorithm
1393  /// \return the standard algorithm name
1394  /// \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms
1395  /// do not have standard names yet. For example, there is no standard algorithm name for
1396  /// Shoup's ECIES.
1397  virtual std::string AlgorithmName() const;
1398 
1399 protected:
1400  const Algorithm & GetAlgorithm() const
1401  {return *static_cast<const MessageAuthenticationCode *>(this);}
1402  virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
1403  {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);}
1404 };
1405 
1406 /// \brief Interface for random number generators
1407 /// \details The library provides a number of random number generators, from software based
1408 /// to hardware based generators.
1409 /// \details All generated values are uniformly distributed over the range specified.
1410 /// \since Crypto++ 3.1
1411 /// \sa <A HREF="https://www.cryptopp.com/wiki/RandomNumberGenerator">RandomNumberGenerator</A>
1412 /// on the Crypto++ wiki
1413 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
1414 {
1415 public:
1416  virtual ~RandomNumberGenerator() {}
1417 
1418  /// \brief Update RNG state with additional unpredictable values
1419  /// \param input the entropy to add to the generator
1420  /// \param length the size of the input buffer
1421  /// \throws NotImplemented
1422  /// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy()
1423  /// to test for the ability to use additional entropy.
1424  /// \details If a derived class does not override IncorporateEntropy(), then the base class
1425  /// throws NotImplemented.
1426  virtual void IncorporateEntropy(const byte *input, size_t length)
1427  {
1428  CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
1429  throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
1430  }
1431 
1432  /// \brief Determines if a generator can accept additional entropy
1433  /// \return true if IncorporateEntropy() is implemented
1434  virtual bool CanIncorporateEntropy() const {return false;}
1435 
1436  /// \brief Generate new random byte and return it
1437  /// \return a random 8-bit byte
1438  /// \details Default implementation calls GenerateBlock() with one byte.
1439  /// \details All generated values are uniformly distributed over the range specified within the
1440  /// the constraints of a particular generator.
1441  virtual byte GenerateByte();
1442 
1443  /// \brief Generate new random bit and return it
1444  /// \return a random bit
1445  /// \details The default implementation calls GenerateByte() and return its lowest bit.
1446  /// \details All generated values are uniformly distributed over the range specified within the
1447  /// the constraints of a particular generator.
1448  virtual unsigned int GenerateBit();
1449 
1450  /// \brief Generate a random 32 bit word in the range min to max, inclusive
1451  /// \param min the lower bound of the range
1452  /// \param max the upper bound of the range
1453  /// \return a random 32-bit word
1454  /// \details The default implementation calls Crop() on the difference between max and
1455  /// min, and then returns the result added to min.
1456  /// \details All generated values are uniformly distributed over the range specified within the
1457  /// the constraints of a particular generator.
1458  virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL);
1459 
1460  /// \brief Generate random array of bytes
1461  /// \param output the byte buffer
1462  /// \param size the length of the buffer, in bytes
1463  /// \details All generated values are uniformly distributed over the range specified within the
1464  /// the constraints of a particular generator.
1465  /// \note A derived generator \a must override either GenerateBlock() or
1466  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1467  virtual void GenerateBlock(byte *output, size_t size);
1468 
1469  /// \brief Generate random bytes into a BufferedTransformation
1470  /// \param target the BufferedTransformation object which receives the bytes
1471  /// \param channel the channel on which the bytes should be pumped
1472  /// \param length the number of bytes to generate
1473  /// \details The default implementation calls GenerateBlock() and pumps the result into
1474  /// the DEFAULT_CHANNEL of the target.
1475  /// \details All generated values are uniformly distributed over the range specified within the
1476  /// the constraints of a particular generator.
1477  /// \note A derived generator \a must override either GenerateBlock() or
1478  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1479  virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
1480 
1481  /// \brief Generate and discard n bytes
1482  /// \param n the number of bytes to generate and discard
1483  virtual void DiscardBytes(size_t n);
1484 
1485  /// \brief Randomly shuffle the specified array
1486  /// \param begin an iterator to the first element in the array
1487  /// \param end an iterator beyond the last element in the array
1488  /// \details The resulting permutation is uniformly distributed.
1489  template <class IT> void Shuffle(IT begin, IT end)
1490  {
1491  // TODO: What happens if there are more than 2^32 elements?
1492  for (; begin != end; ++begin)
1493  std::iter_swap(begin, begin + GenerateWord32(0, static_cast<word32>(end-begin-1)));
1494  }
1495 };
1496 
1497 /// \brief Interface for key derivation functions
1498 /// \since Crypto++ 7.0
1499 /// \sa <A HREF="https://www.cryptopp.com/wiki/KeyDerivationFunction">KeyDerivationFunction</A>
1500 /// on the Crypto++ wiki
1501 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm
1502 {
1503 public:
1504  virtual ~KeyDerivationFunction() {}
1505 
1506  /// \brief Provides the name of this algorithm
1507  /// \return the standard algorithm name
1508  virtual std::string AlgorithmName() const =0;
1509 
1510  /// \brief Determine minimum number of bytes
1511  /// \return Minimum number of bytes which can be derived
1512  virtual size_t MinDerivedKeyLength() const;
1513 
1514  /// \brief Determine maximum number of bytes
1515  /// \return Maximum number of bytes which can be derived
1516  virtual size_t MaxDerivedKeyLength() const;
1517 
1518  /// \brief Returns a valid key length for the derivation function
1519  /// \param keylength the size of the derived key, in bytes
1520  /// \return the valid key length, in bytes
1521  virtual size_t GetValidDerivedLength(size_t keylength) const =0;
1522 
1523  /// \brief Returns whether keylength is a valid key length
1524  /// \param keylength the requested keylength
1525  /// \return true if the derived keylength is valid, false otherwise
1526  /// \details Internally the function calls GetValidKeyLength()
1527  virtual bool IsValidDerivedLength(size_t keylength) const {
1528  return keylength == GetValidDerivedLength(keylength);
1529  }
1530 
1531  /// \brief Derive a key from a seed
1532  /// \param derived the derived output buffer
1533  /// \param derivedLen the size of the derived buffer, in bytes
1534  /// \param secret the seed input buffer
1535  /// \param secretLen the size of the secret buffer, in bytes
1536  /// \param params additional initialization parameters to configure this object
1537  /// \return the number of iterations performed
1538  /// \throws InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme
1539  /// \details DeriveKey() provides a standard interface to derive a key from
1540  /// a secret seed and other parameters. Each class that derives from KeyDerivationFunction
1541  /// provides an overload that accepts most parameters used by the derivation function.
1542  /// \details the number of iterations performed by DeriveKey() may be 1. For example, a
1543  /// scheme like HKDF does not use the iteration count so it returns 1.
1544  virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params = g_nullNameValuePairs) const =0;
1545 
1546  /// \brief Set or change parameters
1547  /// \param params additional initialization parameters to configure this object
1548  /// \details SetParameters() is useful for setting common parameters when an object is
1549  /// reused. Some derivation function classes may choose to implement it.
1550  virtual void SetParameters(const NameValuePairs& params);
1551 
1552 protected:
1553  /// \brief Returns the base class Algorithm
1554  /// \return the base class Algorithm
1555  virtual const Algorithm & GetAlgorithm() const =0;
1556 
1557  /// \brief Validates the derived key length
1558  /// \param length the size of the derived key material, in bytes
1559  /// \throws InvalidKeyLength if the key length is invalid
1560  void ThrowIfInvalidDerivedKeyLength(size_t length) const;
1561 };
1562 
1563 /// \brief Interface for password based key derivation functions
1564 /// \since Crypto++ 7.0
1566 {
1567 };
1568 
1569 /// \brief Random Number Generator that does not produce random numbers
1570 /// \return reference that can be passed to functions that require a RandomNumberGenerator
1571 /// \details NullRNG() returns a reference that can be passed to functions that require a
1572 /// RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented
1573 /// when a generation function is called.
1574 /// \sa ClassNullRNG, PK_SignatureScheme::IsProbabilistic()
1575 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
1576 
1577 class WaitObjectContainer;
1578 class CallStack;
1579 
1580 /// \brief Interface for objects that can be waited on.
1581 class CRYPTOPP_NO_VTABLE Waitable
1582 {
1583 public:
1584  virtual ~Waitable() {}
1585 
1586  /// \brief Maximum number of wait objects that this object can return
1587  /// \return the maximum number of wait objects
1588  virtual unsigned int GetMaxWaitObjectCount() const =0;
1589 
1590  /// \brief Retrieves waitable objects
1591  /// \param container the wait container to receive the references to the objects.
1592  /// \param callStack CallStack() object used to select waitable objects
1593  /// \details GetWaitObjects() is usually called in one of two ways. First, it can
1594  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1595  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1596  /// parameter, it can be called like
1597  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1598  virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
1599 
1600  /// \brief Wait on this object
1601  /// \return true if the wait succeeded, false otherwise
1602  /// \details Wait() is the same as creating an empty container, calling GetWaitObjects(), and then calling
1603  /// Wait() on the container.
1604  bool Wait(unsigned long milliseconds, CallStack const& callStack);
1605 };
1606 
1607 /// \brief Interface for buffered transformations
1608 /// \details BufferedTransformation is a generalization of BlockTransformation,
1609 /// StreamTransformation and HashTransformation.
1610 /// \details A buffered transformation is an object that takes a stream of bytes as input (this may
1611 /// be done in stages), does some computation on them, and then places the result into an internal
1612 /// buffer for later retrieval. Any partial result already in the output buffer is not modified
1613 /// by further input.
1614 /// \details If a method takes a "blocking" parameter, and you pass false for it, then the method
1615 /// will return before all input has been processed if the input cannot be processed without waiting
1616 /// (for network buffers to become available, for example). In this case the method will return true
1617 /// or a non-zero integer value. When this happens you must continue to call the method with the same
1618 /// parameters until it returns false or zero, before calling any other method on it or attached
1619 /// BufferedTransformation. The integer return value in this case is approximately
1620 /// the number of bytes left to be processed, and can be used to implement a progress bar.
1621 /// \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on
1622 /// the signal to attached BufferedTransformation objects, with propagation decremented at each
1623 /// step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation.
1624 /// \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual
1625 /// number of bytes retrieved, which is the lesser of the request number and MaxRetrievable().
1626 /// \details \a Most of the input functions, like Put() and PutWord32(), return the number of
1627 /// bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value
1628 /// means bytes remain to be processed.
1629 /// \nosubgrouping
1630 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
1631 {
1632 public:
1633  virtual ~BufferedTransformation() {}
1634 
1635  /// \brief Construct a BufferedTransformation
1637 
1638  /// \brief Provides a reference to this object
1639  /// \return A reference to this object
1640  /// \details Useful for passing a temporary object to a function that takes a non-const reference
1641  BufferedTransformation& Ref() {return *this;}
1642 
1643  /// \name INPUT
1644  //@{
1645 
1646  /// \brief Input a byte for processing
1647  /// \param inByte the 8-bit byte (octet) to be processed.
1648  /// \param blocking specifies whether the object should block when processing input.
1649  /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
1650  /// 0 indicates all bytes were processed.
1651  /// \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>.
1652  size_t Put(byte inByte, bool blocking=true)
1653  {return Put(&inByte, 1, blocking);}
1654 
1655  /// \brief Input a byte buffer for processing
1656  /// \param inString the byte buffer to process
1657  /// \param length the size of the string, in bytes
1658  /// \param blocking specifies whether the object should block when processing input
1659  /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
1660  /// 0 indicates all bytes were processed.
1661  /// \details Internally, Put() calls Put2().
1662  size_t Put(const byte *inString, size_t length, bool blocking=true)
1663  {return Put2(inString, length, 0, blocking);}
1664 
1665  /// Input a 16-bit word for processing.
1666  /// \param value the 16-bit value to be processed
1667  /// \param order the ByteOrder of the value to be processed.
1668  /// \param blocking specifies whether the object should block when processing input
1669  /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
1670  /// 0 indicates all bytes were processed.
1671  size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1672 
1673  /// Input a 32-bit word for processing.
1674  /// \param value the 32-bit value to be processed.
1675  /// \param order the ByteOrder of the value to be processed.
1676  /// \param blocking specifies whether the object should block when processing input.
1677  /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
1678  /// 0 indicates all bytes were processed.
1679  size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1680 
1681  /// Input a 64-bit word for processing.
1682  /// \param value the 64-bit value to be processed.
1683  /// \param order the ByteOrder of the value to be processed.
1684  /// \param blocking specifies whether the object should block when processing input.
1685  /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
1686  /// 0 indicates all bytes were processed.
1687  size_t PutWord64(word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1688 
1689  /// \brief Request space which can be written into by the caller
1690  /// \param size the requested size of the buffer
1691  /// \return byte pointer to the space to input data
1692  /// \details The purpose of this method is to help avoid extra memory allocations.
1693  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1694  /// size is the requested size of the buffer. When the call returns, size is the size of
1695  /// the array returned to the caller.
1696  /// \details The base class implementation sets size to 0 and returns NULL.
1697  /// \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
1698  /// an ArraySink, the pointer to the array is returned and the size is remaining size.
1699  virtual byte * CreatePutSpace(size_t &size)
1700  {size=0; return NULLPTR;}
1701 
1702  /// \brief Determines whether input can be modified by the callee
1703  /// \return true if input can be modified, false otherwise
1704  /// \details The base class implementation returns false.
1705  virtual bool CanModifyInput() const
1706  {return false;}
1707 
1708  /// \brief Input multiple bytes that may be modified by callee.
1709  /// \param inString the byte buffer to process
1710  /// \param length the size of the string, in bytes
1711  /// \param blocking specifies whether the object should block when processing input
1712  /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
1713  /// bytes were processed.
1714  size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
1715  {return PutModifiable2(inString, length, 0, blocking);}
1716 
1717  /// \brief Signals the end of messages to the object
1718  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1719  /// \param blocking specifies whether the object should block when processing input
1720  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1721  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1722  bool MessageEnd(int propagation=-1, bool blocking=true)
1723  {return !!Put2(NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
1724 
1725  /// \brief Input multiple bytes for processing and signal the end of a message
1726  /// \param inString the byte buffer to process
1727  /// \param length the size of the string, in bytes
1728  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1729  /// \param blocking specifies whether the object should block when processing input
1730  /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
1731  /// bytes were processed.
1732  /// \details Internally, PutMessageEnd() calls Put2() with a modified propagation to
1733  /// ensure all attached transformations finish processing the message.
1734  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1735  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1736  size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
1737  {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
1738 
1739  /// \brief Input multiple bytes for processing
1740  /// \param inString the byte buffer to process
1741  /// \param length the size of the string, in bytes
1742  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
1743  /// \param blocking specifies whether the object should block when processing input
1744  /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
1745  /// bytes were processed.
1746  /// \details Derived classes must implement Put2().
1747  virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
1748 
1749  /// \brief Input multiple bytes that may be modified by callee.
1750  /// \param inString the byte buffer to process.
1751  /// \param length the size of the string, in bytes.
1752  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
1753  /// \param blocking specifies whether the object should block when processing input.
1754  /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
1755  /// bytes were processed.
1756  /// \details Internally, PutModifiable2() calls Put2().
1757  virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
1758  {return Put2(inString, length, messageEnd, blocking);}
1759 
1760  /// \brief Exception thrown by objects that have \a not implemented nonblocking input processing
1761  /// \details BlockingInputOnly inherits from NotImplemented
1763  {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
1764  //@}
1765 
1766  /// \name WAITING
1767  //@{
1768  /// \brief Retrieves the maximum number of waitable objects
1769  unsigned int GetMaxWaitObjectCount() const;
1770 
1771  /// \brief Retrieves waitable objects
1772  /// \param container the wait container to receive the references to the objects
1773  /// \param callStack CallStack() object used to select waitable objects
1774  /// \details GetWaitObjects is usually called in one of two ways. First, it can
1775  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1776  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1777  /// parameter, it can be called like
1778  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1779  void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
1780  //@} // WAITING
1781 
1782  /// \name SIGNALS
1783  //@{
1784 
1785  /// \brief Initialize or reinitialize this object, without signal propagation
1786  /// \param parameters a set of NameValuePairs to initialize this object
1787  /// \throws NotImplemented
1788  /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
1789  /// number of arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1790  /// all possible combintations of configurable parameters.
1791  /// \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization
1792  /// should be propagated, then use the Initialize() function.
1793  /// \details If a derived class does not override IsolatedInitialize(), then the base class throws
1794  /// NotImplemented.
1795  virtual void IsolatedInitialize(const NameValuePairs &parameters) {
1796  CRYPTOPP_UNUSED(parameters);
1797  throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
1798  }
1799 
1800  /// \brief Flushes data buffered by this object, without signal propagation
1801  /// \param hardFlush indicates whether all data should be flushed
1802  /// \param blocking specifies whether the object should block when processing input
1803  /// \return true if the flush was successful, false otherwise
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  /// \return true if the message was successful, false otherwise
1811  virtual bool IsolatedMessageSeriesEnd(bool blocking)
1812  {CRYPTOPP_UNUSED(blocking); return false;}
1813 
1814  /// \brief Initialize or reinitialize this object, with signal propagation
1815  /// \param parameters a set of NameValuePairs to initialize or reinitialize this object
1816  /// \param propagation the number of attached transformations the Initialize() signal should be passed
1817  /// \details Initialize() is used to initialize or reinitialize an object using a variable number of
1818  /// arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1819  /// all possible combintations of configurable parameters.
1820  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1821  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1822  virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
1823 
1824  /// \brief Flush buffered input and/or output, with signal propagation
1825  /// \param hardFlush is used to indicate whether all data should be flushed
1826  /// \param propagation the number of attached transformations the Flush()
1827  /// signal should be passed
1828  /// \param blocking specifies whether the object should block when processing input
1829  /// \return true if the flush was successful, false otherwise
1830  /// \details propagation count includes this object. Setting propagation to
1831  /// <tt>1</tt> means this object only. Setting propagation to <tt>-1</tt>
1832  /// means unlimited propagation.
1833  /// \note Hard flushes must be used with care. It means try to process and
1834  /// output everything, even if there may not be enough data to complete the
1835  /// action. For example, hard flushing a HexDecoder would cause an error if
1836  /// you do it after inputing an odd number of hex encoded characters.
1837  /// \note For some types of filters, like ZlibDecompressor, hard flushes can
1838  /// only be done at "synchronization points". These synchronization points
1839  /// are positions in the data stream that are created by hard flushes on the
1840  /// corresponding reverse filters, in this example ZlibCompressor. This is
1841  /// useful when zlib compressed data is moved across a network in packets
1842  /// and compression state is preserved across packets, as in the SSH2 protocol.
1843  virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
1844 
1845  /// \brief Marks the end of a series of messages, with signal propagation
1846  /// \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
1847  /// \param blocking specifies whether the object should block when processing input
1848  /// \return true if the message was successful, false otherwise
1849  /// \details Each object that receives the signal will perform its processing, decrement
1850  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
1851  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1852  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1853  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
1854  virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
1855 
1856  /// \brief Set propagation of automatically generated and transferred signals
1857  /// \param propagation then new value
1858  /// \details Setting propagation to <tt>0</tt> means do not automatically generate signals. Setting
1859  /// propagation to <tt>-1</tt> means unlimited propagation.
1860  virtual void SetAutoSignalPropagation(int propagation)
1861  {CRYPTOPP_UNUSED(propagation);}
1862 
1863  /// \brief Retrieve automatic signal propagation value
1864  /// \return the number of attached transformations the signal is propagated to. 0 indicates
1865  /// the signal is only witnessed by this object
1866  virtual int GetAutoSignalPropagation() const {return 0;}
1867 public:
1868 
1869  /// \name RETRIEVAL OF ONE MESSAGE
1870  //@{
1871 
1872  /// \brief Provides the number of bytes ready for retrieval
1873  /// \return the number of bytes ready for retrieval
1874  /// \details All retrieval functions return the actual number of bytes retrieved, which is
1875  /// the lesser of the request number and MaxRetrievable()
1876  virtual lword MaxRetrievable() const;
1877 
1878  /// \brief Determines whether bytes are ready for retrieval
1879  /// \return true if bytes are available for retrieval, false otherwise
1880  virtual bool AnyRetrievable() const;
1881 
1882  /// \brief Retrieve a 8-bit byte
1883  /// \param outByte the 8-bit value to be retrieved
1884  /// \return the number of bytes consumed during the call.
1885  /// \details Use the return value of Get to detect short reads.
1886  virtual size_t Get(byte &outByte);
1887 
1888  /// \brief Retrieve a block of bytes
1889  /// \param outString a block of bytes
1890  /// \param getMax the number of bytes to Get
1891  /// \return the number of bytes consumed during the call.
1892  /// \details Use the return value of Get to detect short reads.
1893  virtual size_t Get(byte *outString, size_t getMax);
1894 
1895  /// \brief Peek a 8-bit byte
1896  /// \param outByte the 8-bit value to be retrieved
1897  /// \return the number of bytes read during the call.
1898  /// \details Peek does not remove bytes from the object. Use the return value of
1899  /// Get() to detect short reads.
1900  virtual size_t Peek(byte &outByte) const;
1901 
1902  /// \brief Peek a block of bytes
1903  /// \param outString a block of bytes
1904  /// \param peekMax the number of bytes to Peek
1905  /// \return the number of bytes read during the call.
1906  /// \details Peek does not remove bytes from the object. Use the return value of
1907  /// Peek() to detect short reads.
1908  virtual size_t Peek(byte *outString, size_t peekMax) const;
1909 
1910  /// \brief Retrieve a 16-bit word
1911  /// \param value the 16-bit value to be retrieved
1912  /// \param order the ByteOrder of the value to be processed.
1913  /// \return the number of bytes consumed during the call.
1914  /// \details Use the return value of GetWord16() to detect short reads.
1915  size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1916 
1917  /// \brief Retrieve a 32-bit word
1918  /// \param value the 32-bit value to be retrieved
1919  /// \param order the ByteOrder of the value to be processed.
1920  /// \return the number of bytes consumed during the call.
1921  /// \details Use the return value of GetWord32() to detect short reads.
1922  size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1923 
1924  /// \brief Retrieve a 64-bit word
1925  /// \param value the 64-bit value to be retrieved
1926  /// \param order the ByteOrder of the value to be processed.
1927  /// \return the number of bytes consumed during the call.
1928  /// \details Use the return value of GetWord64() to detect short reads.
1929  /// \since Crypto++ 8.3
1930  size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1931 
1932  /// \brief Peek a 16-bit word
1933  /// \param value the 16-bit value to be retrieved
1934  /// \param order the ByteOrder of the value to be processed.
1935  /// \return the number of bytes consumed during the call.
1936  /// \details Peek does not consume bytes in the stream. Use the return value
1937  /// of PeekWord16() to detect short reads.
1938  size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1939 
1940  /// \brief Peek a 32-bit word
1941  /// \param value the 32-bit value to be retrieved
1942  /// \param order the ByteOrder of the value to be processed.
1943  /// \return the number of bytes consumed during the call.
1944  /// \details Peek does not consume bytes in the stream. Use the return value
1945  /// of PeekWord32() to detect short reads.
1946  size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1947 
1948  /// \brief Peek a 64-bit word
1949  /// \param value the 64-bit value to be retrieved
1950  /// \param order the ByteOrder of the value to be processed.
1951  /// \return the number of bytes consumed during the call.
1952  /// \details Peek does not consume bytes in the stream. Use the return value
1953  /// of PeekWord64() to detect short reads.
1954  /// \since Crypto++ 8.3
1955  size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1956 
1957  /// move transferMax bytes of the buffered output to target as input
1958 
1959  /// \brief Transfer bytes from this object to another BufferedTransformation
1960  /// \param target the destination BufferedTransformation
1961  /// \param transferMax the number of bytes to transfer
1962  /// \param channel the channel on which the transfer should occur
1963  /// \return the number of bytes transferred during the call.
1964  /// \details TransferTo removes bytes from this object and moves them to the destination.
1965  /// \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2().
1966  lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
1967  {TransferTo2(target, transferMax, channel); return transferMax;}
1968 
1969  /// \brief Discard skipMax bytes from the output buffer
1970  /// \param skipMax the number of bytes to discard
1971  /// \details Skip() discards bytes from the output buffer, which is the AttachedTransformation(), if present.
1972  /// The function always returns the parameter <tt>skipMax</tt>.
1973  /// \details If you want to skip bytes from a Source, then perform the following.
1974  /// <pre> StringSource ss(str, false, new Redirector(TheBitBucket()));
1975  /// ss.Pump(10); // Skip 10 bytes from Source
1976  /// ss.Detach(new FilterChain(...));
1977  /// ss.PumpAll();
1978  /// </pre>
1979  virtual lword Skip(lword skipMax=LWORD_MAX);
1980 
1981  /// \brief Copy bytes from this object to another BufferedTransformation
1982  /// \param target the destination BufferedTransformation
1983  /// \param copyMax the number of bytes to copy
1984  /// \param channel the channel on which the transfer should occur
1985  /// \return the number of bytes copied during the call.
1986  /// \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
1987  /// \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2().
1988  lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1989  {return CopyRangeTo(target, 0, copyMax, channel);}
1990 
1991  /// \brief Copy bytes from this object using an index to another BufferedTransformation
1992  /// \param target the destination BufferedTransformation
1993  /// \param position the 0-based index of the byte stream to begin the copying
1994  /// \param copyMax the number of bytes to copy
1995  /// \param channel the channel on which the transfer should occur
1996  /// \return the number of bytes copied during the call.
1997  /// \details CopyTo copies bytes from this object to the destination. The bytes remain in this
1998  /// object. Copying begins at the index position in the current stream, and not from an absolute
1999  /// position in the stream.
2000  /// \details The function returns the new position in the stream after transferring the bytes starting at the index.
2001  lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
2002  {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
2003  //@}
2004 
2005  /// \name RETRIEVAL OF MULTIPLE MESSAGES
2006  //@{
2007 
2008  /// \brief Provides the number of bytes ready for retrieval
2009  /// \return the number of bytes ready for retrieval
2010  virtual lword TotalBytesRetrievable() const;
2011 
2012  /// \brief Provides the number of meesages processed by this object
2013  /// \return the number of meesages processed by this object
2014  /// \details NumberOfMessages returns number of times MessageEnd() has been
2015  /// received minus messages retrieved or skipped
2016  virtual unsigned int NumberOfMessages() const;
2017 
2018  /// \brief Determines if any messages are available for retrieval
2019  /// \return true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
2020  /// \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
2021  virtual bool AnyMessages() const;
2022 
2023  /// \brief Start retrieving the next message
2024  /// \return true if a message is ready for retrieval
2025  /// \details GetNextMessage() returns true if a message is ready for retrieval; false
2026  /// if no more messages exist or this message is not completely retrieved.
2027  virtual bool GetNextMessage();
2028 
2029  /// \brief Skip a number of meessages
2030  /// \param count number of messages to skip
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 copy
2052  /// \param channel the channel on which the copy 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 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 to be processed (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 to be processed (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 to be processed (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  /// \return true if the message was successful, false otherwise
2288  /// \details Each object that receives the signal will perform its processing, decrement
2289  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
2290  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2291  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2292  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
2293  virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
2294 
2295  /// \brief Sets the default retrieval channel
2296  /// \param channel the channel to signal the end of a series of messages
2297  /// \note this function may not be implemented in all objects that should support it.
2298  virtual void SetRetrievalChannel(const std::string &channel);
2299  //@}
2300 
2301  /// \name ATTACHMENT
2302  /// \details Some BufferedTransformation objects (e.g. Filter objects) allow other BufferedTransformation objects to be
2303  /// attached. When this is done, the first object instead of buffering its output, sends that output to the attached
2304  /// object as input. The entire attachment chain is deleted when the anchor object is destructed.
2305 
2306  //@{
2307  /// \brief Determines whether the object allows attachment
2308  /// \return true if the object allows an attachment, false otherwise
2309  /// \details Sources and Filters will returns true, while Sinks and other objects will return false.
2310  virtual bool Attachable() {return false;}
2311 
2312  /// \brief Returns the object immediately attached to this object
2313  /// \return the attached transformation
2314  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2315  /// version of AttachedTransformation() always returns NULL.
2316  virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;}
2317 
2318  /// \brief Returns the object immediately attached to this object
2319  /// \return the attached transformation
2320  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2321  /// version of AttachedTransformation() always returns NULL.
2323  {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
2324 
2325  /// \brief Delete the current attachment chain and attach a new one
2326  /// \param newAttachment the new BufferedTransformation to attach
2327  /// \throws NotImplemented
2328  /// \details Detach() deletes the current attachment chain and replace it with an optional newAttachment
2329  /// \details If a derived class does not override Detach(), then the base class throws
2330  /// NotImplemented.
2331  virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) {
2332  CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable());
2333  throw NotImplemented("BufferedTransformation: this object is not attachable");
2334  }
2335 
2336  /// \brief Add newAttachment to the end of attachment chain
2337  /// \param newAttachment the attachment to add to the end of the chain
2338  virtual void Attach(BufferedTransformation *newAttachment);
2339  //@}
2340 
2341 protected:
2342  /// \brief Decrements the propagation count while clamping at 0
2343  /// \return the decremented propagation or 0
2344  static int DecrementPropagation(int propagation)
2345  {return propagation != 0 ? propagation - 1 : 0;}
2346 
2347 private:
2348  // for ChannelPutWord16, ChannelPutWord32 and ChannelPutWord64,
2349  // to ensure the buffer isn't deallocated before non-blocking
2350  // operation completes
2351  byte m_buf[8];
2352 };
2353 
2354 /// \brief An input discarding BufferedTransformation
2355 /// \return a reference to a BufferedTransformation object that discards all input
2356 CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
2357 
2358 /// \brief Interface for crypto material
2359 /// \details CryptoMaterial() is an interface for crypto material, such as
2360 /// public keys, private keys and crypto parameters. Derived classes generally
2361 /// do not offer public methods such as GenerateRandom() and
2362 /// GenerateRandomWithKeySize().
2363 /// \sa GeneratableCryptoMaterial()
2364 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
2365 {
2366 public:
2367  /// Exception thrown when invalid crypto material is detected
2368  class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
2369  {
2370  public:
2371  explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
2372  };
2373 
2374  virtual ~CryptoMaterial() {}
2375 
2376  /// \brief Assign values to this object
2377  /// \details This function can be used to create a public key from a private key.
2378  virtual void AssignFrom(const NameValuePairs &source) =0;
2379 
2380  /// \brief Check this object for errors
2381  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2382  /// \param level the level of thoroughness
2383  /// \return true if the tests succeed, false otherwise
2384  /// \details There are four levels of thoroughness:
2385  /// <ul>
2386  /// <li>0 - using this object won't cause a crash or exception
2387  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
2388  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
2389  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
2390  /// </ul>
2391  /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
2392  /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
2393  /// \sa ThrowIfInvalid()
2394  virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
2395 
2396  /// \brief Check this object for errors
2397  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2398  /// \param level the level of thoroughness
2399  /// \throws InvalidMaterial
2400  /// \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial() if validation fails.
2401  /// \sa Validate()
2402  virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
2403  {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
2404 
2405  /// \brief Saves a key to a BufferedTransformation
2406  /// \param bt the destination BufferedTransformation
2407  /// \throws NotImplemented
2408  /// \details Save() writes the material to a BufferedTransformation.
2409  /// \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
2410  /// includes an object identifier with an algorthm id, like a subjectPublicKeyInfo.
2411  /// \details A "raw" key without the "key info" can be saved using a key's DEREncode() method.
2412  /// \details If a derived class does not override Save(), then the base class throws
2413  /// NotImplemented().
2414  virtual void Save(BufferedTransformation &bt) const
2415  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
2416 
2417  /// \brief Loads a key from a BufferedTransformation
2418  /// \param bt the source BufferedTransformation
2419  /// \throws KeyingErr
2420  /// \details Load() attempts to read material from a BufferedTransformation. If the
2421  /// material is a key that was generated outside the library, then the following
2422  /// usually applies:
2423  /// <ul>
2424  /// <li>the key should be ASN.1 BER encoded
2425  /// <li>the key should be a "key info"
2426  /// </ul>
2427  /// \details "key info" means the key should have an object identifier with an algorthm id,
2428  /// like a subjectPublicKeyInfo.
2429  /// \details To read a "raw" key without the "key info", then call the key's BERDecode() method.
2430  /// \note Load() generally does not check that the key is valid. Call Validate(), if needed.
2431  virtual void Load(BufferedTransformation &bt)
2432  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
2433 
2434  /// \brief Determines whether the object supports precomputation
2435  /// \return true if the object supports precomputation, false otherwise
2436  /// \sa Precompute()
2437  virtual bool SupportsPrecomputation() const {return false;}
2438 
2439  /// \brief Perform precomputation
2440  /// \param precomputationStorage the suggested number of objects for the precompute table
2441  /// \throws NotImplemented
2442  /// \details The exact semantics of Precompute() varies, but it typically means calculate
2443  /// a table of n objects that can be used later to speed up computation.
2444  /// \details If a derived class does not override Precompute(), then the base class throws
2445  /// NotImplemented.
2446  /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation()
2447  virtual void Precompute(unsigned int precomputationStorage) {
2448  CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation());
2449  throw NotImplemented("CryptoMaterial: this object does not support precomputation");
2450  }
2451 
2452  /// \brief Retrieve previously saved precomputation
2453  /// \param storedPrecomputation BufferedTransformation with the saved precomputation
2454  /// \throws NotImplemented
2455  /// \sa SupportsPrecomputation(), Precompute()
2456  virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
2457  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2458 
2459  /// \brief Save precomputation for later use
2460  /// \param storedPrecomputation BufferedTransformation to write the precomputation
2461  /// \throws NotImplemented
2462  /// \sa SupportsPrecomputation(), Precompute()
2463  virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
2464  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2465 
2466  /// \brief Perform a quick sanity check
2467  /// \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users.
2468  void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
2469 
2470 #if defined(__SUNPRO_CC)
2471  // Sun Studio 11/CC 5.8 workaround: it generates incorrect code
2472  // when casting to an empty virtual base class. JW, 2018: It is
2473  // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable
2474  // it everywhere in case it affects SPARC (which we don't test).
2475  char m_sunCCworkaround;
2476 #endif
2477 };
2478 
2479 /// \brief Interface for crypto material
2480 /// \details GeneratableCryptoMaterial() is an interface for crypto material,
2481 /// such as private keys and crypto parameters. Derived classes offer public
2482 /// methods such as GenerateRandom() and GenerateRandomWithKeySize().
2483 /// \sa CryptoMaterial()
2484 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
2485 {
2486 public:
2487  virtual ~GeneratableCryptoMaterial() {}
2488 
2489  /// \brief Generate a random key or crypto parameters
2490  /// \param rng a RandomNumberGenerator to produce keying material
2491  /// \param params additional initialization parameters
2492  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2493  /// \details If a derived class does not override GenerateRandom(), then the base class throws
2494  /// NotImplemented.
2495  virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs) {
2496  CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
2497  throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
2498  }
2499 
2500  /// \brief Generate a random key or crypto parameters
2501  /// \param rng a RandomNumberGenerator to produce keying material
2502  /// \param keySize the size of the key, in bits
2503  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2504  /// \details GenerateRandomWithKeySize calls GenerateRandom() with a NameValuePairs
2505  /// object with only "KeySize"
2506  void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
2507 };
2508 
2509 /// \brief Interface for public keys
2510 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
2511 {
2512 };
2513 
2514 /// \brief Interface for private keys
2515 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
2516 {
2517 };
2518 
2519 /// \brief Interface for crypto prameters
2520 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
2521 {
2522 };
2523 
2524 /// \brief Interface for certificates
2525 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Certificate : virtual public CryptoMaterial
2526 {
2527 };
2528 
2529 /// \brief Interface for asymmetric algorithms
2530 /// \details BERDecode() and DEREncode() were removed under Issue 569
2531 /// and Commit 9b174e84de7a. Programs should use <tt>AccessMaterial().Load(bt)</tt>
2532 /// or <tt>AccessMaterial().Save(bt)</tt> instead.
2533 /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/569">Issue 569</A>
2534 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
2535 {
2536 public:
2537  virtual ~AsymmetricAlgorithm() {}
2538 
2539  /// \brief Retrieves a reference to CryptoMaterial
2540  /// \return a reference to the crypto material
2541  virtual CryptoMaterial & AccessMaterial() =0;
2542 
2543  /// \brief Retrieves a reference to CryptoMaterial
2544  /// \return a const reference to the crypto material
2545  virtual const CryptoMaterial & GetMaterial() const =0;
2546 
2547 #if 0
2548  /// \brief Loads this object from a BufferedTransformation
2549  /// \param bt a BufferedTransformation object
2550  /// \details Use of BERDecode() changed to Load() at Issue 569.
2551  /// \deprecated for backwards compatibility, calls <tt>AccessMaterial().Load(bt)</tt>
2552  void BERDecode(BufferedTransformation &bt)
2553  {AccessMaterial().Load(bt);}
2554 
2555  /// \brief Saves this object to a BufferedTransformation
2556  /// \param bt a BufferedTransformation object
2557  /// \details Use of DEREncode() changed to Save() at Issue 569.
2558  /// \deprecated for backwards compatibility, calls GetMaterial().Save(bt)
2559  void DEREncode(BufferedTransformation &bt) const
2560  {GetMaterial().Save(bt);}
2561 #endif
2562 };
2563 
2564 /// \brief Interface for asymmetric algorithms using public keys
2565 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
2566 {
2567 public:
2568  virtual ~PublicKeyAlgorithm() {}
2569 
2570  // VC60 workaround: no co-variant return type
2571 
2572  /// \brief Retrieves a reference to a Public Key
2573  /// \return a reference to the public key
2575  {return AccessPublicKey();}
2576  /// \brief Retrieves a reference to a Public Key
2577  /// \return a const reference the public key
2578  const CryptoMaterial & GetMaterial() const
2579  {return GetPublicKey();}
2580 
2581  /// \brief Retrieves a reference to a Public Key
2582  /// \return a reference to the public key
2583  virtual PublicKey & AccessPublicKey() =0;
2584  /// \brief Retrieves a reference to a Public Key
2585  /// \return a const reference the public key
2586  virtual const PublicKey & GetPublicKey() const
2587  {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
2588 };
2589 
2590 /// \brief Interface for asymmetric algorithms using private keys
2591 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
2592 {
2593 public:
2594  virtual ~PrivateKeyAlgorithm() {}
2595 
2596  /// \brief Retrieves a reference to a Private Key
2597  /// \return a reference the private key
2598  CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
2599  /// \brief Retrieves a reference to a Private Key
2600  /// \return a const reference the private key
2601  const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
2602 
2603  /// \brief Retrieves a reference to a Private Key
2604  /// \return a reference the private key
2605  virtual PrivateKey & AccessPrivateKey() =0;
2606  /// \brief Retrieves a reference to a Private Key
2607  /// \return a const reference the private key
2608  virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
2609 };
2610 
2611 /// \brief Interface for key agreement algorithms
2612 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
2613 {
2614 public:
2615  virtual ~KeyAgreementAlgorithm() {}
2616 
2617  /// \brief Retrieves a reference to Crypto Parameters
2618  /// \return a reference the crypto parameters
2619  CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
2620  /// \brief Retrieves a reference to Crypto Parameters
2621  /// \return a const reference the crypto parameters
2622  const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
2623 
2624  /// \brief Retrieves a reference to Crypto Parameters
2625  /// \return a reference the crypto parameters
2626  virtual CryptoParameters & AccessCryptoParameters() =0;
2627  /// \brief Retrieves a reference to Crypto Parameters
2628  /// \return a const reference the crypto parameters
2629  virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
2630 };
2631 
2632 /// \brief Interface for public-key encryptors and decryptors
2633 /// \details This class provides an interface common to encryptors and decryptors
2634 /// for querying their plaintext and ciphertext lengths.
2635 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
2636 {
2637 public:
2638  virtual ~PK_CryptoSystem() {}
2639 
2640  /// \brief Provides the maximum length of plaintext for a given ciphertext length
2641  /// \return the maximum size of the plaintext, in bytes
2642  /// \details This function returns 0 if ciphertextLength is not valid (too long or too short).
2643  virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
2644 
2645  /// \brief Calculate the length of ciphertext given length of plaintext
2646  /// \return the maximum size of the ciphertext, in bytes
2647  /// \details This function returns 0 if plaintextLength is not valid (too long).
2648  virtual size_t CiphertextLength(size_t plaintextLength) const =0;
2649 
2650  /// \brief Determines whether this object supports the use of a named parameter
2651  /// \param name the name of the parameter
2652  /// \return true if the parameter name is supported, false otherwise
2653  /// \details Some possible parameter names: EncodingParameters(), KeyDerivationParameters()
2654  /// and others Parameters listed in argnames.h
2655  virtual bool ParameterSupported(const char *name) const =0;
2656 
2657  /// \brief Provides the fixed ciphertext length, if one exists
2658  /// \return the fixed ciphertext length if one exists, otherwise 0
2659  /// \details "Fixed" here means length of ciphertext does not depend on length of plaintext.
2660  /// In this case, it usually does depend on the key length.
2661  virtual size_t FixedCiphertextLength() const {return 0;}
2662 
2663  /// \brief Provides the maximum plaintext length given a fixed ciphertext length
2664  /// \return maximum plaintext length given the fixed ciphertext length, if one exists,
2665  /// otherwise return 0.
2666  /// \details FixedMaxPlaintextLength(0 returns the maximum plaintext length given the fixed ciphertext
2667  /// length, if one exists, otherwise return 0.
2668  virtual size_t FixedMaxPlaintextLength() const {return 0;}
2669 };
2670 
2671 /// \brief Interface for public-key encryptors
2672 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
2673 {
2674 public:
2675  /// \brief Exception thrown when trying to encrypt plaintext of invalid length
2676  class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
2677  {
2678  public:
2679  InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
2680  };
2681 
2682  /// \brief Encrypt a byte string
2683  /// \param rng a RandomNumberGenerator derived class
2684  /// \param plaintext the plaintext byte buffer
2685  /// \param plaintextLength the size of the plaintext byte buffer
2686  /// \param ciphertext a byte buffer to hold the encrypted string
2687  /// \param parameters a set of NameValuePairs to initialize this object
2688  /// \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
2689  /// \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
2690  /// byte buffer is large enough.
2691  /// \sa PK_Decryptor
2692  virtual void Encrypt(RandomNumberGenerator &rng,
2693  const byte *plaintext, size_t plaintextLength,
2694  byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2695 
2696  /// \brief Create a new encryption filter
2697  /// \param rng a RandomNumberGenerator derived class
2698  /// \param attachment an attached transformation
2699  /// \param parameters a set of NameValuePairs to initialize this object
2700  /// \details \p attachment can be \p NULL. The caller is responsible for deleting the returned pointer.
2701  /// Encoding parameters should be passed in the "EP" channel.
2702  virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
2703  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2704 };
2705 
2706 /// \brief Interface for public-key decryptors
2707 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
2708 {
2709 public:
2710  virtual ~PK_Decryptor() {}
2711 
2712  /// \brief Decrypt a byte string
2713  /// \param rng a RandomNumberGenerator derived class
2714  /// \param ciphertext the encrypted byte buffer
2715  /// \param ciphertextLength the size of the encrypted byte buffer
2716  /// \param plaintext a byte buffer to hold the decrypted string
2717  /// \param parameters a set of NameValuePairs to initialize this object
2718  /// \return the result of the decryption operation
2719  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2720  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2721  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2722  /// is undefined.
2723  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2724  /// byte buffer is large enough
2725  /// \sa PK_Encryptor
2726  virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
2727  const byte *ciphertext, size_t ciphertextLength,
2728  byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2729 
2730  /// \brief Create a new decryption filter
2731  /// \param rng a RandomNumberGenerator derived class
2732  /// \param attachment an attached transformation
2733  /// \param parameters a set of NameValuePairs to initialize this object
2734  /// \return the newly created decryption filter
2735  /// \note the caller is responsible for deleting the returned pointer
2736  virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
2737  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2738 
2739  /// \brief Decrypt a fixed size ciphertext
2740  /// \param rng a RandomNumberGenerator derived class
2741  /// \param ciphertext the encrypted byte buffer
2742  /// \param plaintext a byte buffer to hold the decrypted string
2743  /// \param parameters a set of NameValuePairs to initialize this object
2744  /// \return the result of the decryption operation
2745  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2746  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2747  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2748  /// is undefined.
2749  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2750  /// byte buffer is large enough
2751  /// \sa PK_Encryptor
2752  DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
2753  {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
2754 };
2755 
2756 /// \brief Interface for public-key signers and verifiers
2757 /// \details This class provides an interface common to signers and verifiers for querying scheme properties
2758 /// \sa DL_SignatureSchemeBase, TF_SignatureSchemeBase, DL_SignerBase, TF_SignerBase
2759 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
2760 {
2761 public:
2762  /// \brief Exception throw when the private or public key has a length that can't be used
2763  /// \details InvalidKeyLength() may be thrown by any function in this class if the private
2764  /// or public key has a length that can't be used
2765  class CRYPTOPP_DLL InvalidKeyLength : public Exception
2766  {
2767  public:
2768  InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
2769  };
2770 
2771  /// \brief Exception throw when the private or public key is too short to sign or verify
2772  /// \details KeyTooShort() may be thrown by any function in this class if the private or public
2773  /// key is too short to sign or verify anything
2774  class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
2775  {
2776  public:
2777  KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
2778  };
2779 
2780  virtual ~PK_SignatureScheme() {}
2781 
2782  /// \brief Provides the signature length if it only depends on the key
2783  /// \return the signature length if it only depends on the key, in bytes
2784  /// \details SignatureLength() returns the signature length if it only depends on the key, otherwise 0.
2785  virtual size_t SignatureLength() const =0;
2786 
2787  /// \brief Provides the maximum signature length produced given the length of the recoverable message part
2788  /// \param recoverablePartLength the length of the recoverable message part, in bytes
2789  /// \return the maximum signature length produced for a given length of recoverable message part, in bytes
2790  /// \details MaxSignatureLength() returns the maximum signature length produced given the length of the
2791  /// recoverable message part.
2792  virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
2793  {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
2794 
2795  /// \brief Provides the length of longest message that can be recovered
2796  /// \return the length of longest message that can be recovered, in bytes
2797  /// \details MaxRecoverableLength() returns the length of longest message that can be recovered, or 0 if
2798  /// this signature scheme does not support message recovery.
2799  virtual size_t MaxRecoverableLength() const =0;
2800 
2801  /// \brief Provides the length of longest message that can be recovered from a signature of given length
2802  /// \param signatureLength the length of the signature, in bytes
2803  /// \return the length of longest message that can be recovered from a signature of given length, in bytes
2804  /// \details MaxRecoverableLengthFromSignatureLength() returns the length of longest message that can be
2805  /// recovered from a signature of given length, or 0 if this signature scheme does not support message
2806  /// recovery.
2807  virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
2808 
2809  /// \brief Determines whether a signature scheme requires a random number generator
2810  /// \return true if the signature scheme requires a RandomNumberGenerator() to sign
2811  /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take
2812  /// RandomNumberGenerator().
2813  virtual bool IsProbabilistic() const =0;
2814 
2815  /// \brief Determines whether the non-recoverable message part can be signed
2816  /// \return true if the non-recoverable message part can be signed
2817  virtual bool AllowNonrecoverablePart() const =0;
2818 
2819  /// \brief Determines whether the signature must be input before the message
2820  /// \return true if the signature must be input before the message during verifcation
2821  /// \details if SignatureUpfront() returns true, then you must input the signature before the message
2822  /// during verification. Otherwise you can input the signature at anytime.
2823  virtual bool SignatureUpfront() const {return false;}
2824 
2825  /// \brief Determines whether the recoverable part must be input before the non-recoverable part
2826  /// \return true if the recoverable part must be input before the non-recoverable part during signing
2827  /// \details RecoverablePartFirst() determines whether you must input the recoverable part before the
2828  /// non-recoverable part during signing
2829  virtual bool RecoverablePartFirst() const =0;
2830 };
2831 
2832 /// \brief Interface for accumulating messages to be signed or verified
2833 /// \details Only Update() should be called from the PK_MessageAccumulator() class. No other functions
2834 /// inherited from HashTransformation, like DigestSize() and TruncatedFinal(), should be called.
2835 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
2836 {
2837 public:
2838  /// \warning DigestSize() should not be called on PK_MessageAccumulator
2839  unsigned int DigestSize() const
2840  {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
2841 
2842  /// \warning TruncatedFinal() should not be called on PK_MessageAccumulator
2843  void TruncatedFinal(byte *digest, size_t digestSize)
2844  {
2845  CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
2846  throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
2847  }
2848 };
2849 
2850 /// \brief Interface for public-key signers
2851 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
2852 {
2853 public:
2854  virtual ~PK_Signer() {}
2855 
2856  /// \brief Create a new HashTransformation to accumulate the message to be signed
2857  /// \param rng a RandomNumberGenerator derived class
2858  /// \return a pointer to a PK_MessageAccumulator
2859  /// \details NewSignatureAccumulator() can be used with all signing methods. Sign() will autimatically delete the
2860  /// accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2861  virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
2862 
2863  /// \brief Input a recoverable message to an accumulator
2864  /// \param messageAccumulator a reference to a PK_MessageAccumulator
2865  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2866  /// \param recoverableMessageLength the size of the recoverable message part
2867  virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
2868 
2869  /// \brief Sign and delete the messageAccumulator
2870  /// \param rng a RandomNumberGenerator derived class
2871  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2872  /// \param signature a block of bytes for the signature
2873  /// \return actual signature length
2874  /// \details Sign() deletes the messageAccumulator, even if an exception is thrown.
2875  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2876  virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
2877 
2878  /// \brief Sign and restart messageAccumulator
2879  /// \param rng a RandomNumberGenerator derived class
2880  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2881  /// \param signature a block of bytes for the signature
2882  /// \param restart flag indicating whether the messageAccumulator should be restarted
2883  /// \return actual signature length
2884  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2885  virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
2886 
2887  /// \brief Sign a message
2888  /// \param rng a RandomNumberGenerator derived class
2889  /// \param message a pointer to the message
2890  /// \param messageLen the size of the message to be signed
2891  /// \param signature a block of bytes for the signature
2892  /// \return actual signature length
2893  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2894  virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
2895 
2896  /// \brief Sign a recoverable message
2897  /// \param rng a RandomNumberGenerator derived class
2898  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2899  /// \param recoverableMessageLength the size of the recoverable message part
2900  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2901  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2902  /// \param signature a block of bytes for the signature
2903  /// \return actual signature length
2904  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength(recoverableMessageLength)</tt>
2905  virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
2906  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
2907 };
2908 
2909 /// \brief Interface for public-key signature verifiers
2910 /// \details The Recover* functions throw NotImplemented if the signature scheme does not support
2911 /// message recovery.
2912 /// \details The Verify* functions throw InvalidDataFormat if the scheme does support message
2913 /// recovery and the signature contains a non-empty recoverable message part. The
2914 /// Recover* functions should be used in that case.
2915 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
2916 {
2917 public:
2918  virtual ~PK_Verifier() {}
2919 
2920  /// \brief Create a new HashTransformation to accumulate the message to be verified
2921  /// \return a pointer to a PK_MessageAccumulator
2922  /// \details NewVerificationAccumulator() can be used with all verification methods. Verify() will autimatically delete
2923  /// the accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2924  virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
2925 
2926  /// \brief Input signature into a message accumulator
2927  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2928  /// \param signature the signature on the message
2929  /// \param signatureLength the size of the signature
2930  virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
2931 
2932  /// \brief Check whether messageAccumulator contains a valid signature and message
2933  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2934  /// \return true if the signature is valid, false otherwise
2935  /// \details Verify() deletes the messageAccumulator, even if an exception is thrown.
2936  virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
2937 
2938  /// \brief Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
2939  /// \param messageAccumulator a reference to a PK_MessageAccumulator derived class
2940  /// \return true if the signature is valid, false otherwise
2941  /// \details VerifyAndRestart() restarts the messageAccumulator
2942  virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
2943 
2944  /// \brief Check whether input signature is a valid signature for input message
2945  /// \param message a pointer to the message to be verified
2946  /// \param messageLen the size of the message
2947  /// \param signature a pointer to the signature over the message
2948  /// \param signatureLen the size of the signature
2949  /// \return true if the signature is valid, false otherwise
2950  virtual bool VerifyMessage(const byte *message, size_t messageLen,
2951  const byte *signature, size_t signatureLen) const;
2952 
2953  /// \brief Recover a message from its signature
2954  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2955  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2956  /// \return the result of the verification operation
2957  /// \details Recover() deletes the messageAccumulator, even if an exception is thrown.
2958  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2959  virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
2960 
2961  /// \brief Recover a message from its signature
2962  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2963  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2964  /// \return the result of the verification operation
2965  /// \details RecoverAndRestart() restarts the messageAccumulator
2966  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2967  virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
2968 
2969  /// \brief Recover a message from its signature
2970  /// \param recoveredMessage a pointer for the recovered message
2971  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2972  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2973  /// \param signature the signature on the message
2974  /// \param signatureLength the size of the signature
2975  /// \return the result of the verification operation
2976  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2977  virtual DecodingResult RecoverMessage(byte *recoveredMessage,
2978  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
2979  const byte *signature, size_t signatureLength) const;
2980 };
2981 
2982 /// \brief Interface for domains of simple key agreement protocols
2983 /// \details A key agreement domain is a set of parameters that must be shared
2984 /// by two parties in a key agreement protocol, along with the algorithms
2985 /// for generating key pairs and deriving agreed values.
2986 /// \since Crypto++ 3.0
2987 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
2988 {
2989 public:
2990  virtual ~SimpleKeyAgreementDomain() {}
2991 
2992  /// \brief Provides the size of the agreed value
2993  /// \return size of agreed value produced in this domain
2994  virtual unsigned int AgreedValueLength() const =0;
2995 
2996  /// \brief Provides the size of the private key
2997  /// \return size of private keys in this domain
2998  virtual unsigned int PrivateKeyLength() const =0;
2999 
3000  /// \brief Provides the size of the public key
3001  /// \return size of public keys in this domain
3002  virtual unsigned int PublicKeyLength() const =0;
3003 
3004  /// \brief Generate private key in this domain
3005  /// \param rng a RandomNumberGenerator derived class
3006  /// \param privateKey a byte buffer for the generated private key in this domain
3007  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3008  virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3009 
3010  /// \brief Generate a public key from a private key in this domain
3011  /// \param rng a RandomNumberGenerator derived class
3012  /// \param privateKey a byte buffer with the previously generated private key
3013  /// \param publicKey a byte buffer for the generated public key in this domain
3014  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
3015  virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3016 
3017  /// \brief Generate a private/public key pair
3018  /// \param rng a RandomNumberGenerator derived class
3019  /// \param privateKey a byte buffer for the generated private key in this domain
3020  /// \param publicKey a byte buffer for the generated public key in this domain
3021  /// \details GenerateKeyPair() is equivalent to calling GeneratePrivateKey() and then GeneratePublicKey().
3022  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3023  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
3024  virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3025 
3026  /// \brief Derive agreed value
3027  /// \param agreedValue a byte buffer for the shared secret
3028  /// \param privateKey a byte buffer with your private key in this domain
3029  /// \param otherPublicKey a byte buffer with the other party's public key in this domain
3030  /// \param validateOtherPublicKey a flag indicating if the other party's public key should be validated
3031  /// \return true upon success, false in case of failure
3032  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3033  /// \details The other party's public key is validated by default. If you have previously validated the
3034  /// static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3035  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3036  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3037  /// \pre <tt>COUNTOF(otherPublicKey) == PublicKeyLength()</tt>
3038  virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
3039 };
3040 
3041 /// \brief Interface for domains of authenticated key agreement protocols
3042 /// \details In an authenticated key agreement protocol, each party has two
3043 /// key pairs. The long-lived key pair is called the static key pair,
3044 /// and the short-lived key pair is called the ephemeral key pair.
3045 /// \since Crypto++ 3.0
3046 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3047 {
3048 public:
3049  virtual ~AuthenticatedKeyAgreementDomain() {}
3050 
3051  /// \brief Provides the size of the agreed value
3052  /// \return size of agreed value produced in this domain
3053  virtual unsigned int AgreedValueLength() const =0;
3054 
3055  /// \brief Provides the size of the static private key
3056  /// \return size of static private keys in this domain
3057  virtual unsigned int StaticPrivateKeyLength() const =0;
3058 
3059  /// \brief Provides the size of the static public key
3060  /// \return size of static public keys in this domain
3061  virtual unsigned int StaticPublicKeyLength() const =0;
3062 
3063  /// \brief Generate static private key in this domain
3064  /// \param rng a RandomNumberGenerator derived class
3065  /// \param privateKey a byte buffer for the generated private key in this domain
3066  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3067  virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3068 
3069  /// \brief Generate a static public key from a private key in this domain
3070  /// \param rng a RandomNumberGenerator derived class
3071  /// \param privateKey a byte buffer with the previously generated private key
3072  /// \param publicKey a byte buffer for the generated public key in this domain
3073  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3074  virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3075 
3076  /// \brief Generate a static private/public key pair
3077  /// \param rng a RandomNumberGenerator derived class
3078  /// \param privateKey a byte buffer for the generated private key in this domain
3079  /// \param publicKey a byte buffer for the generated public key in this domain
3080  /// \details GenerateStaticKeyPair() is equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey().
3081  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3082  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3083  virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3084 
3085  /// \brief Provides the size of ephemeral private key
3086  /// \return the size of ephemeral private key in this domain
3087  virtual unsigned int EphemeralPrivateKeyLength() const =0;
3088 
3089  /// \brief Provides the size of ephemeral public key
3090  /// \return the size of ephemeral public key in this domain
3091  virtual unsigned int EphemeralPublicKeyLength() const =0;
3092 
3093  /// \brief Generate ephemeral private key
3094  /// \param rng a RandomNumberGenerator derived class
3095  /// \param privateKey a byte buffer for the generated private key in this domain
3096  /// \pre <tt>COUNTOF(privateKey) == PrivateEphemeralKeyLength()</tt>
3097  virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3098 
3099  /// \brief Generate ephemeral public key
3100  /// \param rng a RandomNumberGenerator derived class
3101  /// \param privateKey a byte buffer for the generated private key in this domain
3102  /// \param publicKey a byte buffer for the generated public key in this domain
3103  /// \pre <tt>COUNTOF(publicKey) == PublicEphemeralKeyLength()</tt>
3104  virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3105 
3106  /// \brief Generate private/public key pair
3107  /// \param rng a RandomNumberGenerator derived class
3108  /// \param privateKey a byte buffer for the generated private key in this domain
3109  /// \param publicKey a byte buffer for the generated public key in this domain
3110  /// \details GenerateEphemeralKeyPair() is equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey()
3111  virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3112 
3113  /// \brief Derive agreed value
3114  /// \param agreedValue a byte buffer for the shared secret
3115  /// \param staticPrivateKey a byte buffer with your static private key in this domain
3116  /// \param ephemeralPrivateKey a byte buffer with your ephemeral private key in this domain
3117  /// \param staticOtherPublicKey a byte buffer with the other party's static public key in this domain
3118  /// \param ephemeralOtherPublicKey a byte buffer with the other party's ephemeral public key in this domain
3119  /// \param validateStaticOtherPublicKey a flag indicating if the other party's public key should be validated
3120  /// \return true upon success, false in case of failure
3121  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3122  /// \details The other party's ephemeral public key is validated by default. If you have previously validated
3123  /// the static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3124  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3125  /// \pre <tt>COUNTOF(staticPrivateKey) == StaticPrivateKeyLength()</tt>
3126  /// \pre <tt>COUNTOF(ephemeralPrivateKey) == EphemeralPrivateKeyLength()</tt>
3127  /// \pre <tt>COUNTOF(staticOtherPublicKey) == StaticPublicKeyLength()</tt>
3128  /// \pre <tt>COUNTOF(ephemeralOtherPublicKey) == EphemeralPublicKeyLength()</tt>
3129  virtual bool Agree(byte *agreedValue,
3130  const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
3131  const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
3132  bool validateStaticOtherPublicKey=true) const =0;
3133 };
3134 
3135 // interface for password authenticated key agreement protocols, not implemented yet
3136 #if 0
3137 /// \brief Interface for protocol sessions
3138 /*! The methods should be called in the following order:
3139 
3140  InitializeSession(rng, parameters); // or call initialize method in derived class
3141  while (true)
3142  {
3143  if (OutgoingMessageAvailable())
3144  {
3145  length = GetOutgoingMessageLength();
3146  GetOutgoingMessage(message);
3147  ; // send outgoing message
3148  }
3149 
3150  if (LastMessageProcessed())
3151  break;
3152 
3153  ; // receive incoming message
3154  ProcessIncomingMessage(message);
3155  }
3156  ; // call methods in derived class to obtain result of protocol session
3157 */
3158 class ProtocolSession
3159 {
3160 public:
3161  /// Exception thrown when an invalid protocol message is processed
3162  class ProtocolError : public Exception
3163  {
3164  public:
3165  ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
3166  };
3167 
3168  /// Exception thrown when a function is called unexpectedly
3169  /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
3170  class UnexpectedMethodCall : public Exception
3171  {
3172  public:
3173  UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
3174  };
3175 
3176  virtual ~ProtocolSession() {}
3177 
3178  ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {}
3179 
3180  virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
3181 
3182  bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
3183  void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
3184 
3185  bool HasValidState() const {return m_validState;}
3186 
3187  virtual bool OutgoingMessageAvailable() const =0;
3188  virtual unsigned int GetOutgoingMessageLength() const =0;
3189  virtual void GetOutgoingMessage(byte *message) =0;
3190 
3191  virtual bool LastMessageProcessed() const =0;
3192  virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
3193 
3194 protected:
3195  void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
3196  void CheckAndHandleInvalidState() const;
3197  void SetValidState(bool valid) {m_validState = valid;}
3198 
3199  RandomNumberGenerator *m_rng;
3200 
3201 private:
3202  bool m_throwOnProtocolError, m_validState;
3203 };
3204 
3205 class KeyAgreementSession : public ProtocolSession
3206 {
3207 public:
3208  virtual ~KeyAgreementSession() {}
3209 
3210  virtual unsigned int GetAgreedValueLength() const =0;
3211  virtual void GetAgreedValue(byte *agreedValue) const =0;
3212 };
3213 
3214 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
3215 {
3216 public:
3217  virtual ~PasswordAuthenticatedKeyAgreementSession() {}
3218 
3219  void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
3220  const byte *myId, unsigned int myIdLength,
3221  const byte *counterPartyId, unsigned int counterPartyIdLength,
3222  const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
3223 };
3224 
3225 /// \brief Password based key agreement domain
3226 /// \since Crypto++ 3.0
3227 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3228 {
3229 public:
3230  virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
3231 
3232  /// return whether the domain parameters stored in this object are valid
3233  virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
3234  {return GetCryptoParameters().Validate(rng, 2);}
3235 
3236  virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
3237  virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
3238 
3239  enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
3240 
3241  virtual bool IsValidRole(unsigned int role) =0;
3242  virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
3243 };
3244 #endif
3245 
3246 /// \brief Exception thrown when an ASN.1 BER decoing error is encountered
3247 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
3248 {
3249 public:
3250  BERDecodeErr() : InvalidArgument("BER decode error") {}
3251  BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
3252 };
3253 
3254 /// \brief Interface for encoding and decoding ASN1 objects
3255 /// \details Each class that derives from ASN1Object should provide a serialization format
3256 /// that controls subobject layout. Most of the time the serialization format is
3257 /// taken from a standard, like P1363 or an RFC.
3258 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
3259 {
3260 public:
3261  virtual ~ASN1Object() {}
3262 
3263  /// \brief Decode this object from a BufferedTransformation
3264  /// \param bt BufferedTransformation object
3265  /// \details Uses Basic Encoding Rules (BER)
3266  virtual void BERDecode(BufferedTransformation &bt) =0;
3267 
3268  /// \brief Encode this object into a BufferedTransformation
3269  /// \param bt BufferedTransformation object
3270  /// \details Uses Distinguished Encoding Rules (DER)
3271  virtual void DEREncode(BufferedTransformation &bt) const =0;
3272 
3273  /// \brief Encode this object into a BufferedTransformation
3274  /// \param bt BufferedTransformation object
3275  /// \details Uses Basic Encoding Rules (BER).
3276  /// \details This may be useful if DEREncode() would be too inefficient.
3277  virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
3278 };
3279 
3280 /// \brief Specifies the build-time version of the library
3281 /// \return integer representing the build-time version
3282 /// \details LibraryVersion can help detect inadvertent mixing and matching of library
3283 /// versions. When using Crypto++ distributed by a third party, LibraryVersion()
3284 /// records the version of the shared object that was built by the third party.
3285 /// The LibraryVersion() record resides in <tt>cryptlib.o</tt> on Unix compatibles
3286 /// and <tt>cryptlib.obj</tt> on Windows. It does not change when an app links
3287 /// to the library.
3288 /// \details LibraryVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3289 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3290 /// the library version is 5.7 or above. If it is missing, then the library version is
3291 /// 5.6.5 or below.
3292 /// \details The function could be used as shown below.
3293 /// <pre> 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 /// \return 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> if (LibraryVersion() != HeaderVersion())
3325 /// {
3326 /// cout << "Potential version mismatch" << endl;
3327 ///
3328 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3329 /// const int lmin = (LibraryVersion() / 10U) % 10;
3330 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3331 /// const int hmin = (HeaderVersion() / 10U) % 10;
3332 ///
3333 /// if(lmaj != hmaj)
3334 /// cout << "Major version mismatch" << endl;
3335 /// else if(lmin != hmin)
3336 /// cout << "Minor version mismatch" << endl;
3337 /// }
3338 /// </pre>
3339 /// \sa LibraryVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3340 /// \since Crypto++ 6.0
3341 extern "C" {
3342 inline int HeaderVersion()
3343 {
3344  return CRYPTOPP_VERSION;
3345 }
3346 } // C linkage
3347 
3348 NAMESPACE_END
3349 
3350 #if CRYPTOPP_MSC_VERSION
3351 # pragma warning(pop)
3352 #endif
3353 
3354 #endif
virtual unsigned int BlockSize() const
Provides the block size of the compression function.
Definition: cryptlib.h:1165
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:3342
Exception thrown when invalid crypto material is detected.
Definition: cryptlib.h:2368
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition: cryptlib.h:2447
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:708
unsigned int TagSize() const
Provides the tag size of the hash.
Definition: cryptlib.h:1157
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:1527
Interface for message authentication codes.
Definition: cryptlib.h:1294
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:2534
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition: cryptlib.h:771
Namespace containing NaCl library functions.
Definition: cryptlib.h:568
virtual bool NeedsPrespecifiedDataLengths() const
Determines if data lengths must be specified prior to inputting data.
Definition: cryptlib.h:1348
Interface for public-key encryptors and decryptors.
Definition: cryptlib.h:2635
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:2402
The IV is set by the object.
Definition: cryptlib.h:727
The operating system reported an error.
Definition: cryptlib.h:252
Interface for authenticated encryption modes of operation.
Definition: cryptlib.h:1316
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:2431
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:1795
Exception thrown when the object is in the wrong state for the operation.
Definition: cryptlib.h:1324
const CryptoMaterial & GetMaterial() const
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2622
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:2851
Interface for public-key encryptors.
Definition: cryptlib.h:2672
virtual bool CanModifyInput() const
Determines whether input can be modified by the callee.
Definition: cryptlib.h:1705
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:744
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:2752
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:2598
Interface for asymmetric algorithms using private keys.
Definition: cryptlib.h:2591
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:1265
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:594
CipherDir GetCipherDirection() const
Provides the direction of the cipher.
Definition: cryptlib.h:940
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:1413
Common C++ header files.
void ProcessString(byte *inoutString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1060
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:2586
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1866
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this hash.
Definition: cryptlib.h:1172
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:1630
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:2515
virtual const BufferedTransformation * AttachedTransformation() const
Returns the object immediately attached to this object.
Definition: cryptlib.h:2322
Interface for cloning objects.
Definition: cryptlib.h:584
virtual size_t FixedCiphertextLength() const
Provides the fixed ciphertext length, if one exists.
Definition: cryptlib.h:2661
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:2001
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:1278
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:636
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:1581
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:1714
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: cryptlib.h:2463
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:2468
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:1054
bool MessageEnd(int propagation=-1, bool blocking=true)
Signals the end of messages to the object.
Definition: cryptlib.h:1722
Interface for domains of simple key agreement protocols.
Definition: cryptlib.h:2987
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2601
bool CanUsePredictableIVs() const
Determines if the object can use random but possibly predictable IVs.
Definition: cryptlib.h:749
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:2456
Exception thrown when trying to encrypt plaintext of invalid length.
Definition: cryptlib.h:2676
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:1966
Interface for public-key decryptors.
Definition: cryptlib.h:2707
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:2774
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1652
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:1147
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition: cryptlib.h:776
unsigned int DigestSize() const
Definition: cryptlib.h:2839
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:672
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:3258
StreamTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:953
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition: cryptlib.h:783
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:965
void ProcessString(byte *outString, const byte *inString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1068
virtual unsigned int GetOptimalBlockSizeUsed() const
Provides the number of bytes used in the current block when processing at optimal block size...
Definition: cryptlib.h:976
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:1636
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:1286
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:879
Exception throw when the private or public key has a length that can&#39;t be used.
Definition: cryptlib.h:2765
Interface for algorithms that take byte strings as keys.
Definition: cryptlib.h:641
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:2316
HashTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:1120
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:1860
Interface for asymmetric algorithms using public keys.
Definition: cryptlib.h:2565
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:761
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:529
Namespace containing testing and benchmark classes.
Definition: cryptlib.h:575
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
Definition: cryptlib.h:1434
bool CanUseStructuredIVs() const
Determines if the object can use structured IVs.
Definition: cryptlib.h:755
Interface for public-key signers and verifiers.
Definition: cryptlib.h:2759
Interface for the data processing portion of stream ciphers.
Definition: cryptlib.h:945
virtual void Detach(BufferedTransformation *newAttachment=NULL)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:2331
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:1200
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:619
#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:1236
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:1811
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:598
size_t Put(const byte *inString, size_t length, bool blocking=true)
Input a byte buffer for processing.
Definition: cryptlib.h:1662
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2835
unsigned int DefaultIVLength() const
Provides the default size of an IV.
Definition: cryptlib.h:766
A decryption filter encountered invalid ciphertext.
Definition: cryptlib.h:222
Interface for key agreement algorithms.
Definition: cryptlib.h:2612
Exception thrown by objects that have not implemented nonblocking input processing.
Definition: cryptlib.h:1762
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:1188
virtual void Seek(lword pos)
Seek to an absolute position.
Definition: cryptlib.h:1086
void ProcessBlock(byte *inoutBlock) const
Encrypt or decrypt a block in place.
Definition: cryptlib.h:888
IV_Requirement
Secure IVs requirements as enumerated values.
Definition: cryptlib.h:719
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2574
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:2629
Interface for public-key signature verifiers.
Definition: cryptlib.h:2915
virtual bool IsPermutation() const
Determines if the transformation is a permutation.
Definition: cryptlib.h:902
virtual byte * CreateUpdateSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1135
void Shuffle(IT begin, IT end)
Randomly shuffle the specified array.
Definition: cryptlib.h:1489
lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
Copy bytes from this object to another BufferedTransformation.
Definition: cryptlib.h:1988
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:1112
Interface for crypto material.
Definition: cryptlib.h:2364
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1699
Interface for certificates.
Definition: cryptlib.h:2525
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2495
Interface for password based key derivation functions.
Definition: cryptlib.h:1565
CryptoMaterial & AccessMaterial()
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2619
An invalid argument was detected.
Definition: cryptlib.h:167
Interface for crypto material.
Definition: cryptlib.h:2484
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:1736
Interface for crypto prameters.
Definition: cryptlib.h:2520
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:1641
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:2510
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:855
FlagsForAdvancedProcessBlocks
Bit flags that control AdvancedProcessBlocks() behavior.
Definition: cryptlib.h:915
The IV must be random and unpredictable.
Definition: cryptlib.h:725
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition: cryptlib.h:740
Interface for domains of authenticated key agreement protocols.
Definition: cryptlib.h:3046
virtual bool GetNextMessageSeries()
Retrieve the next message in a series.
Definition: cryptlib.h:2080
void TruncatedFinal(byte *digest, size_t digestSize)
Definition: cryptlib.h:2843
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:1074
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:3277
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:2414
virtual bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: cryptlib.h:2437
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:1757
virtual void Final(byte *digest)
Computes the hash of the current message.
Definition: cryptlib.h:1142
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:1341
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this cipher.
Definition: cryptlib.h:972
virtual const PrivateKey & GetPrivateKey() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2608
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2578
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:2792
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:2310
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:1216
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:2823
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: cryptlib.h:1426
InvalidCiphertext(const std::string &s)
Construct an InvalidCiphertext.
Definition: cryptlib.h:228
Interface for key derivation functions.
Definition: cryptlib.h:1501
virtual size_t FixedMaxPlaintextLength() const
Provides the maximum plaintext length given a fixed ciphertext length.
Definition: cryptlib.h:2668
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:1021
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:3247
The IV must be random and possibly predictable.
Definition: cryptlib.h:723
virtual unsigned int OptimalNumberOfParallelBlocks() const
Determines the number of blocks that can be processed in parallel.
Definition: cryptlib.h:912
const std::string & GetWhat() const
Retrieves a string describing the exception.
Definition: cryptlib.h:188