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 The number of bytes available are dependent on the source. If an exact value is
1875  /// available, then the exact value is returned. The exact value can include 0 if the source
1876  /// is exhausted.
1877  /// \details Some stream-based sources do not allow seeking() on the underlying stream, such
1878  /// as some FileSource(). If the stream does not allow seeking() then MaxRetrievable()
1879  /// returns LWORD_MAX to indicate there are still bytes to be retrieved.
1880  virtual lword MaxRetrievable() const;
1881 
1882  /// \brief Determines whether bytes are ready for retrieval
1883  /// \return true if bytes are available for retrieval, false otherwise
1884  virtual bool AnyRetrievable() const;
1885 
1886  /// \brief Retrieve a 8-bit byte
1887  /// \param outByte the 8-bit value to be retrieved
1888  /// \return the number of bytes consumed during the call.
1889  /// \details Use the return value of Get to detect short reads.
1890  virtual size_t Get(byte &outByte);
1891 
1892  /// \brief Retrieve a block of bytes
1893  /// \param outString a block of bytes
1894  /// \param getMax the number of bytes to Get
1895  /// \return the number of bytes consumed during the call.
1896  /// \details Use the return value of Get to detect short reads.
1897  virtual size_t Get(byte *outString, size_t getMax);
1898 
1899  /// \brief Peek a 8-bit byte
1900  /// \param outByte the 8-bit value to be retrieved
1901  /// \return the number of bytes read during the call.
1902  /// \details Peek does not remove bytes from the object. Use the return value of
1903  /// Get() to detect short reads.
1904  virtual size_t Peek(byte &outByte) const;
1905 
1906  /// \brief Peek a block of bytes
1907  /// \param outString a block of bytes
1908  /// \param peekMax the number of bytes to Peek
1909  /// \return the number of bytes read during the call.
1910  /// \details Peek does not remove bytes from the object. Use the return value of
1911  /// Peek() to detect short reads.
1912  virtual size_t Peek(byte *outString, size_t peekMax) const;
1913 
1914  /// \brief Retrieve a 16-bit word
1915  /// \param value the 16-bit value to be retrieved
1916  /// \param order the ByteOrder of the value to be processed.
1917  /// \return the number of bytes consumed during the call.
1918  /// \details Use the return value of GetWord16() to detect short reads.
1919  size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1920 
1921  /// \brief Retrieve a 32-bit word
1922  /// \param value the 32-bit value to be retrieved
1923  /// \param order the ByteOrder of the value to be processed.
1924  /// \return the number of bytes consumed during the call.
1925  /// \details Use the return value of GetWord32() to detect short reads.
1926  size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1927 
1928  /// \brief Retrieve a 64-bit word
1929  /// \param value the 64-bit value to be retrieved
1930  /// \param order the ByteOrder of the value to be processed.
1931  /// \return the number of bytes consumed during the call.
1932  /// \details Use the return value of GetWord64() to detect short reads.
1933  /// \since Crypto++ 8.3
1934  size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1935 
1936  /// \brief Peek a 16-bit word
1937  /// \param value the 16-bit value to be retrieved
1938  /// \param order the ByteOrder of the value to be processed.
1939  /// \return the number of bytes consumed during the call.
1940  /// \details Peek does not consume bytes in the stream. Use the return value
1941  /// of PeekWord16() to detect short reads.
1942  size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1943 
1944  /// \brief Peek a 32-bit word
1945  /// \param value the 32-bit value to be retrieved
1946  /// \param order the ByteOrder of the value to be processed.
1947  /// \return the number of bytes consumed during the call.
1948  /// \details Peek does not consume bytes in the stream. Use the return value
1949  /// of PeekWord32() to detect short reads.
1950  size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1951 
1952  /// \brief Peek a 64-bit word
1953  /// \param value the 64-bit value to be retrieved
1954  /// \param order the ByteOrder of the value to be processed.
1955  /// \return the number of bytes consumed during the call.
1956  /// \details Peek does not consume bytes in the stream. Use the return value
1957  /// of PeekWord64() to detect short reads.
1958  /// \since Crypto++ 8.3
1959  size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1960 
1961  /// move transferMax bytes of the buffered output to target as input
1962 
1963  /// \brief Transfer bytes from this object to another BufferedTransformation
1964  /// \param target the destination BufferedTransformation
1965  /// \param transferMax the number of bytes to transfer
1966  /// \param channel the channel on which the transfer should occur
1967  /// \return the number of bytes transferred during the call.
1968  /// \details TransferTo removes bytes from this object and moves them to the destination.
1969  /// \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2().
1970  lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
1971  {TransferTo2(target, transferMax, channel); return transferMax;}
1972 
1973  /// \brief Discard skipMax bytes from the output buffer
1974  /// \param skipMax the number of bytes to discard
1975  /// \details Skip() discards bytes from the output buffer, which is the AttachedTransformation(), if present.
1976  /// The function always returns the parameter <tt>skipMax</tt>.
1977  /// \details If you want to skip bytes from a Source, then perform the following.
1978  /// <pre> StringSource ss(str, false, new Redirector(TheBitBucket()));
1979  /// ss.Pump(10); // Skip 10 bytes from Source
1980  /// ss.Detach(new FilterChain(...));
1981  /// ss.PumpAll();
1982  /// </pre>
1983  virtual lword Skip(lword skipMax=LWORD_MAX);
1984 
1985  /// \brief Copy bytes from this object to another BufferedTransformation
1986  /// \param target the destination BufferedTransformation
1987  /// \param copyMax the number of bytes to copy
1988  /// \param channel the channel on which the transfer should occur
1989  /// \return the number of bytes copied during the call.
1990  /// \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
1991  /// \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2().
1992  lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1993  {return CopyRangeTo(target, 0, copyMax, channel);}
1994 
1995  /// \brief Copy bytes from this object using an index to another BufferedTransformation
1996  /// \param target the destination BufferedTransformation
1997  /// \param position the 0-based index of the byte stream to begin the copying
1998  /// \param copyMax the number of bytes to copy
1999  /// \param channel the channel on which the transfer should occur
2000  /// \return the number of bytes copied during the call.
2001  /// \details CopyTo copies bytes from this object to the destination. The bytes remain in this
2002  /// object. Copying begins at the index position in the current stream, and not from an absolute
2003  /// position in the stream.
2004  /// \details The function returns the new position in the stream after transferring the bytes starting at the index.
2005  lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
2006  {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
2007  //@}
2008 
2009  /// \name RETRIEVAL OF MULTIPLE MESSAGES
2010  //@{
2011 
2012  /// \brief Provides the number of bytes ready for retrieval
2013  /// \return the number of bytes ready for retrieval
2014  virtual lword TotalBytesRetrievable() const;
2015 
2016  /// \brief Provides the number of meesages processed by this object
2017  /// \return the number of meesages processed by this object
2018  /// \details NumberOfMessages returns number of times MessageEnd() has been
2019  /// received minus messages retrieved or skipped
2020  virtual unsigned int NumberOfMessages() const;
2021 
2022  /// \brief Determines if any messages are available for retrieval
2023  /// \return true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
2024  /// \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
2025  virtual bool AnyMessages() const;
2026 
2027  /// \brief Start retrieving the next message
2028  /// \return true if a message is ready for retrieval
2029  /// \details GetNextMessage() returns true if a message is ready for retrieval; false
2030  /// if no more messages exist or this message is not completely retrieved.
2031  virtual bool GetNextMessage();
2032 
2033  /// \brief Skip a number of meessages
2034  /// \param count number of messages to skip
2035  /// \return 0 if the requested number of messages was skipped, non-0 otherwise
2036  /// \details SkipMessages() skips count number of messages. If there is an AttachedTransformation()
2037  /// then SkipMessages() is called on the attached transformation. If there is no attached
2038  /// transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo().
2039  virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
2040 
2041  /// \brief Transfer messages from this object to another BufferedTransformation
2042  /// \param target the destination BufferedTransformation
2043  /// \param count the number of messages to transfer
2044  /// \param channel the channel on which the transfer should occur
2045  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2046  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2047  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
2048  /// bytes is returned. TransferMessagesTo() does not proceed to the next message.
2049  /// \details A return value of 0 indicates all messages were successfully transferred.
2050  unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
2051  {TransferMessagesTo2(target, count, channel); return count;}
2052 
2053  /// \brief Copy messages from this object to another BufferedTransformation
2054  /// \param target the destination BufferedTransformation
2055  /// \param count the number of messages to copy
2056  /// \param channel the channel on which the copy should occur
2057  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2058  /// \details CopyMessagesTo copies messages from this object to the destination.
2059  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
2060  /// bytes is returned. CopyMessagesTo() does not proceed to the next message.
2061  /// \details A return value of 0 indicates all messages were successfully copied.
2062  unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
2063 
2064  /// \brief Skip all messages in the series
2065  virtual void SkipAll();
2066 
2067  /// \brief Transfer all bytes from this object to another BufferedTransformation
2068  /// \param target the destination BufferedTransformation
2069  /// \param channel the channel on which the transfer should occur
2070  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2071  /// Internally TransferAllTo() calls TransferAllTo2().
2072  void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
2073  {TransferAllTo2(target, channel);}
2074 
2075  /// \brief Copy messages from this object to another BufferedTransformation
2076  /// \param target the destination BufferedTransformation
2077  /// \param channel the channel on which the transfer should occur
2078  /// \details CopyAllTo copies messages from this object and copies them to the destination.
2079  void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
2080 
2081  /// \brief Retrieve the next message in a series
2082  /// \return true if a message was retreved, false otherwise
2083  /// \details Internally, the base class implementation returns false.
2084  virtual bool GetNextMessageSeries() {return false;}
2085  /// \brief Provides the number of messages in a series
2086  /// \return the number of messages in this series
2087  virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
2088  /// \brief Provides the number of messages in a series
2089  /// \return the number of messages in this series
2090  virtual unsigned int NumberOfMessageSeries() const {return 0;}
2091  //@}
2092 
2093  /// \name NON-BLOCKING TRANSFER OF OUTPUT
2094  //@{
2095 
2096  // upon return, byteCount contains number of bytes that have finished being transferred,
2097  // and returns the number of bytes left in the current transfer block
2098 
2099  /// \brief Transfer bytes from this object to another BufferedTransformation
2100  /// \param target the destination BufferedTransformation
2101  /// \param byteCount the number of bytes to transfer
2102  /// \param channel the channel on which the transfer should occur
2103  /// \param blocking specifies whether the object should block when processing input
2104  /// \return the number of bytes that remain in the transfer block (i.e., bytes not transferred)
2105  /// \details TransferTo2() removes bytes from this object and moves them to the destination.
2106  /// Transfer begins at the index position in the current stream, and not from an absolute
2107  /// position in the stream.
2108  /// \details byteCount is an \a IN and \a OUT parameter. When the call is made,
2109  /// byteCount is the requested size of the transfer. When the call returns, byteCount is
2110  /// the number of bytes that were transferred.
2111  virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
2112 
2113  // upon return, begin contains the start position of data yet to be finished copying,
2114  // and returns the number of bytes left in the current transfer block
2115 
2116  /// \brief Copy bytes from this object to another BufferedTransformation
2117  /// \param target the destination BufferedTransformation
2118  /// \param begin the 0-based index of the first byte to copy in the stream
2119  /// \param end the 0-based index of the last byte to copy in the stream
2120  /// \param channel the channel on which the transfer should occur
2121  /// \param blocking specifies whether the object should block when processing input
2122  /// \return the number of bytes that remain in the copy block (i.e., bytes not copied)
2123  /// \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not
2124  /// removed from this object. Copying begins at the index position in the current stream, and
2125  /// not from an absolute position in the stream.
2126  /// \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the
2127  /// starting position of the copy. When the call returns, begin is the position of the first
2128  /// byte that was \a not copied (which may be different than end). begin can be used for
2129  /// subsequent calls to CopyRangeTo2().
2130  virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
2131 
2132  // upon return, messageCount contains number of messages that have finished being transferred,
2133  // and returns the number of bytes left in the current transfer block
2134 
2135  /// \brief Transfer messages from this object to another BufferedTransformation
2136  /// \param target the destination BufferedTransformation
2137  /// \param messageCount the number of messages to transfer
2138  /// \param channel the channel on which the transfer should occur
2139  /// \param blocking specifies whether the object should block when processing input
2140  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2141  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2142  /// \details messageCount is an \a IN and \a OUT parameter. When the call is made, messageCount is the
2143  /// the number of messages requested to be transferred. When the call returns, messageCount is the
2144  /// number of messages actually transferred.
2145  size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2146 
2147  // returns the number of bytes left in the current transfer block
2148 
2149  /// \brief Transfer all bytes from this object to another BufferedTransformation
2150  /// \param target the destination BufferedTransformation
2151  /// \param channel the channel on which the transfer should occur
2152  /// \param blocking specifies whether the object should block when processing input
2153  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2154  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2155  size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2156  //@}
2157 
2158  /// \name CHANNELS
2159  //@{
2160  /// \brief Exception thrown when a filter does not support named channels
2162  {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
2163  /// \brief Exception thrown when a filter does not recognize a named channel
2165  {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
2166 
2167  /// \brief Input a byte for processing on a channel
2168  /// \param channel the channel to process the data.
2169  /// \param inByte the 8-bit byte (octet) to be processed.
2170  /// \param blocking specifies whether the object should block when processing input.
2171  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2172  /// number of bytes that were not processed.
2173  size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
2174  {return ChannelPut(channel, &inByte, 1, blocking);}
2175 
2176  /// \brief Input a byte buffer for processing on a channel
2177  /// \param channel the channel to process the data
2178  /// \param inString the byte buffer to process
2179  /// \param length the size of the string, in bytes
2180  /// \param blocking specifies whether the object should block when processing input
2181  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2182  /// number of bytes that were not processed.
2183  size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
2184  {return ChannelPut2(channel, inString, length, 0, blocking);}
2185 
2186  /// \brief Input multiple bytes that may be modified by callee on a channel
2187  /// \param channel the channel to process the data.
2188  /// \param inString the byte buffer to process
2189  /// \param length the size of the string, in bytes
2190  /// \param blocking specifies whether the object should block when processing input
2191  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2192  /// number of bytes that were not processed.
2193  size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
2194  {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
2195 
2196  /// \brief Input a 16-bit word for processing on a channel.
2197  /// \param channel the channel to process the data.
2198  /// \param value the 16-bit value to be processed.
2199  /// \param order the ByteOrder of the value to be processed.
2200  /// \param blocking specifies whether the object should block when processing input.
2201  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2202  /// number of bytes that were not processed.
2203  size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2204 
2205  /// \brief Input a 32-bit word for processing on a channel.
2206  /// \param channel the channel to process the data.
2207  /// \param value the 32-bit value to be processed.
2208  /// \param order the ByteOrder of the value to be processed.
2209  /// \param blocking specifies whether the object should block when processing input.
2210  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2211  /// number of bytes that were not processed.
2212  size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2213 
2214  /// \brief Input a 64-bit word for processing on a channel.
2215  /// \param channel the channel to process the data.
2216  /// \param value the 64-bit value to be processed.
2217  /// \param order the ByteOrder of the value to be processed.
2218  /// \param blocking specifies whether the object should block when processing input.
2219  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2220  /// number of bytes that were not processed.
2221  size_t ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2222 
2223  /// \brief Signal the end of a message
2224  /// \param channel the channel to process the data.
2225  /// \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed
2226  /// \param blocking specifies whether the object should block when processing input
2227  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2228  /// number of bytes that were not processed.
2229  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2230  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2231  bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
2232  {return !!ChannelPut2(channel, NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
2233 
2234  /// \brief Input multiple bytes for processing and signal the end of a message
2235  /// \param channel the channel to process the data.
2236  /// \param inString the byte buffer to process
2237  /// \param length the size of the string, in bytes
2238  /// \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed
2239  /// \param blocking specifies whether the object should block when processing input
2240  /// \return the number of bytes that remain to be processed (i.e., bytes not processed)
2241  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2242  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2243  size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
2244  {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
2245 
2246  /// \brief Request space which can be written into by the caller
2247  /// \param channel the channel to process the data
2248  /// \param size the requested size of the buffer
2249  /// \return a pointer to a memory block with length size
2250  /// \details The purpose of this method is to help avoid extra memory allocations.
2251  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
2252  /// size is the requested size of the buffer. When the call returns, size is the size of
2253  /// the array returned to the caller.
2254  /// \details The base class implementation sets size to 0 and returns NULL.
2255  /// \note Some objects, like ArraySink(), cannot create a space because its fixed. In the case of
2256  /// an ArraySink(), the pointer to the array is returned and the size is remaining size.
2257  virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
2258 
2259  /// \brief Input multiple bytes for processing on a channel.
2260  /// \param channel the channel to process the data.
2261  /// \param inString the byte buffer to process.
2262  /// \param length the size of the string, in bytes.
2263  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
2264  /// \param blocking specifies whether the object should block when processing input.
2265  /// \return the number of bytes that remain to be processed (i.e., bytes not processed)
2266  virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
2267 
2268  /// \brief Input multiple bytes that may be modified by callee on a channel
2269  /// \param channel the channel to process the data
2270  /// \param inString the byte buffer to process
2271  /// \param length the size of the string, in bytes
2272  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
2273  /// \param blocking specifies whether the object should block when processing input
2274  /// \return the number of bytes that remain to be processed (i.e., bytes not processed)
2275  virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
2276 
2277  /// \brief Flush buffered input and/or output on a channel
2278  /// \param channel the channel to flush the data
2279  /// \param hardFlush is used to indicate whether all data should be flushed
2280  /// \param propagation the number of attached transformations the ChannelFlush() signal should be passed
2281  /// \param blocking specifies whether the object should block when processing input
2282  /// \return true of the Flush was successful
2283  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2284  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2285  virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
2286 
2287  /// \brief Marks the end of a series of messages on a channel
2288  /// \param channel the channel to signal the end of a series of messages
2289  /// \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed
2290  /// \param blocking specifies whether the object should block when processing input
2291  /// \return true if the message was successful, false otherwise
2292  /// \details Each object that receives the signal will perform its processing, decrement
2293  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
2294  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2295  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2296  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
2297  virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
2298 
2299  /// \brief Sets the default retrieval channel
2300  /// \param channel the channel to signal the end of a series of messages
2301  /// \note this function may not be implemented in all objects that should support it.
2302  virtual void SetRetrievalChannel(const std::string &channel);
2303  //@}
2304 
2305  /// \name ATTACHMENT
2306  /// \details Some BufferedTransformation objects (e.g. Filter objects) allow other BufferedTransformation objects to be
2307  /// attached. When this is done, the first object instead of buffering its output, sends that output to the attached
2308  /// object as input. The entire attachment chain is deleted when the anchor object is destructed.
2309 
2310  //@{
2311  /// \brief Determines whether the object allows attachment
2312  /// \return true if the object allows an attachment, false otherwise
2313  /// \details Sources and Filters will returns true, while Sinks and other objects will return false.
2314  virtual bool Attachable() {return false;}
2315 
2316  /// \brief Returns the object immediately attached to this object
2317  /// \return the attached transformation
2318  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2319  /// version of AttachedTransformation() always returns NULL.
2320  virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;}
2321 
2322  /// \brief Returns the object immediately attached to this object
2323  /// \return the attached transformation
2324  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2325  /// version of AttachedTransformation() always returns NULL.
2327  {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
2328 
2329  /// \brief Delete the current attachment chain and attach a new one
2330  /// \param newAttachment the new BufferedTransformation to attach
2331  /// \throws NotImplemented
2332  /// \details Detach() deletes the current attachment chain and replace it with an optional newAttachment
2333  /// \details If a derived class does not override Detach(), then the base class throws
2334  /// NotImplemented.
2335  virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) {
2336  CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable());
2337  throw NotImplemented("BufferedTransformation: this object is not attachable");
2338  }
2339 
2340  /// \brief Add newAttachment to the end of attachment chain
2341  /// \param newAttachment the attachment to add to the end of the chain
2342  virtual void Attach(BufferedTransformation *newAttachment);
2343  //@}
2344 
2345 protected:
2346  /// \brief Decrements the propagation count while clamping at 0
2347  /// \return the decremented propagation or 0
2348  static int DecrementPropagation(int propagation)
2349  {return propagation != 0 ? propagation - 1 : 0;}
2350 
2351 private:
2352  // for ChannelPutWord16, ChannelPutWord32 and ChannelPutWord64,
2353  // to ensure the buffer isn't deallocated before non-blocking
2354  // operation completes
2355  byte m_buf[8];
2356 };
2357 
2358 /// \brief An input discarding BufferedTransformation
2359 /// \return a reference to a BufferedTransformation object that discards all input
2360 CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
2361 
2362 /// \brief Interface for crypto material
2363 /// \details CryptoMaterial() is an interface for crypto material, such as
2364 /// public keys, private keys and crypto parameters. Derived classes generally
2365 /// do not offer public methods such as GenerateRandom() and
2366 /// GenerateRandomWithKeySize().
2367 /// \sa GeneratableCryptoMaterial()
2368 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
2369 {
2370 public:
2371  /// Exception thrown when invalid crypto material is detected
2372  class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
2373  {
2374  public:
2375  explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
2376  };
2377 
2378  virtual ~CryptoMaterial() {}
2379 
2380  /// \brief Assign values to this object
2381  /// \details This function can be used to create a public key from a private key.
2382  virtual void AssignFrom(const NameValuePairs &source) =0;
2383 
2384  /// \brief Check this object for errors
2385  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2386  /// \param level the level of thoroughness
2387  /// \return true if the tests succeed, false otherwise
2388  /// \details There are four levels of thoroughness:
2389  /// <ul>
2390  /// <li>0 - using this object won't cause a crash or exception
2391  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
2392  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
2393  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
2394  /// </ul>
2395  /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
2396  /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
2397  /// \sa ThrowIfInvalid()
2398  virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
2399 
2400  /// \brief Check this object for errors
2401  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2402  /// \param level the level of thoroughness
2403  /// \throws InvalidMaterial
2404  /// \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial() if validation fails.
2405  /// \sa Validate()
2406  virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
2407  {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
2408 
2409  /// \brief Saves a key to a BufferedTransformation
2410  /// \param bt the destination BufferedTransformation
2411  /// \throws NotImplemented
2412  /// \details Save() writes the material to a BufferedTransformation.
2413  /// \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
2414  /// includes an object identifier with an algorthm id, like a subjectPublicKeyInfo.
2415  /// \details A "raw" key without the "key info" can be saved using a key's DEREncode() method.
2416  /// \details If a derived class does not override Save(), then the base class throws
2417  /// NotImplemented().
2418  virtual void Save(BufferedTransformation &bt) const
2419  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
2420 
2421  /// \brief Loads a key from a BufferedTransformation
2422  /// \param bt the source BufferedTransformation
2423  /// \throws KeyingErr
2424  /// \details Load() attempts to read material from a BufferedTransformation. If the
2425  /// material is a key that was generated outside the library, then the following
2426  /// usually applies:
2427  /// <ul>
2428  /// <li>the key should be ASN.1 BER encoded
2429  /// <li>the key should be a "key info"
2430  /// </ul>
2431  /// \details "key info" means the key should have an object identifier with an algorthm id,
2432  /// like a subjectPublicKeyInfo.
2433  /// \details To read a "raw" key without the "key info", then call the key's BERDecode() method.
2434  /// \note Load() generally does not check that the key is valid. Call Validate(), if needed.
2435  virtual void Load(BufferedTransformation &bt)
2436  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
2437 
2438  /// \brief Determines whether the object supports precomputation
2439  /// \return true if the object supports precomputation, false otherwise
2440  /// \sa Precompute()
2441  virtual bool SupportsPrecomputation() const {return false;}
2442 
2443  /// \brief Perform precomputation
2444  /// \param precomputationStorage the suggested number of objects for the precompute table
2445  /// \throws NotImplemented
2446  /// \details The exact semantics of Precompute() varies, but it typically means calculate
2447  /// a table of n objects that can be used later to speed up computation.
2448  /// \details If a derived class does not override Precompute(), then the base class throws
2449  /// NotImplemented.
2450  /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation()
2451  virtual void Precompute(unsigned int precomputationStorage) {
2452  CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation());
2453  throw NotImplemented("CryptoMaterial: this object does not support precomputation");
2454  }
2455 
2456  /// \brief Retrieve previously saved precomputation
2457  /// \param storedPrecomputation BufferedTransformation with the saved precomputation
2458  /// \throws NotImplemented
2459  /// \sa SupportsPrecomputation(), Precompute()
2460  virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
2461  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2462 
2463  /// \brief Save precomputation for later use
2464  /// \param storedPrecomputation BufferedTransformation to write the precomputation
2465  /// \throws NotImplemented
2466  /// \sa SupportsPrecomputation(), Precompute()
2467  virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
2468  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2469 
2470  /// \brief Perform a quick sanity check
2471  /// \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users.
2472  void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
2473 
2474 #if defined(__SUNPRO_CC)
2475  // Sun Studio 11/CC 5.8 workaround: it generates incorrect code
2476  // when casting to an empty virtual base class. JW, 2018: It is
2477  // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable
2478  // it everywhere in case it affects SPARC (which we don't test).
2479  char m_sunCCworkaround;
2480 #endif
2481 };
2482 
2483 /// \brief Interface for crypto material
2484 /// \details GeneratableCryptoMaterial() is an interface for crypto material,
2485 /// such as private keys and crypto parameters. Derived classes offer public
2486 /// methods such as GenerateRandom() and GenerateRandomWithKeySize().
2487 /// \sa CryptoMaterial()
2488 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
2489 {
2490 public:
2491  virtual ~GeneratableCryptoMaterial() {}
2492 
2493  /// \brief Generate a random key or crypto parameters
2494  /// \param rng a RandomNumberGenerator to produce keying material
2495  /// \param params additional initialization parameters
2496  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2497  /// \details If a derived class does not override GenerateRandom(), then the base class throws
2498  /// NotImplemented.
2499  virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs) {
2500  CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
2501  throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
2502  }
2503 
2504  /// \brief Generate a random key or crypto parameters
2505  /// \param rng a RandomNumberGenerator to produce keying material
2506  /// \param keySize the size of the key, in bits
2507  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2508  /// \details GenerateRandomWithKeySize calls GenerateRandom() with a NameValuePairs
2509  /// object with only "KeySize"
2510  void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
2511 };
2512 
2513 /// \brief Interface for public keys
2514 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
2515 {
2516 };
2517 
2518 /// \brief Interface for private keys
2519 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
2520 {
2521 };
2522 
2523 /// \brief Interface for crypto prameters
2524 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
2525 {
2526 };
2527 
2528 /// \brief Interface for certificates
2529 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Certificate : virtual public CryptoMaterial
2530 {
2531 };
2532 
2533 /// \brief Interface for asymmetric algorithms
2534 /// \details BERDecode() and DEREncode() were removed under Issue 569
2535 /// and Commit 9b174e84de7a. Programs should use <tt>AccessMaterial().Load(bt)</tt>
2536 /// or <tt>AccessMaterial().Save(bt)</tt> instead.
2537 /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/569">Issue 569</A>
2538 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
2539 {
2540 public:
2541  virtual ~AsymmetricAlgorithm() {}
2542 
2543  /// \brief Retrieves a reference to CryptoMaterial
2544  /// \return a reference to the crypto material
2545  virtual CryptoMaterial & AccessMaterial() =0;
2546 
2547  /// \brief Retrieves a reference to CryptoMaterial
2548  /// \return a const reference to the crypto material
2549  virtual const CryptoMaterial & GetMaterial() const =0;
2550 
2551 #if 0
2552  /// \brief Loads this object from a BufferedTransformation
2553  /// \param bt a BufferedTransformation object
2554  /// \details Use of BERDecode() changed to Load() at Issue 569.
2555  /// \deprecated for backwards compatibility, calls <tt>AccessMaterial().Load(bt)</tt>
2556  void BERDecode(BufferedTransformation &bt)
2557  {AccessMaterial().Load(bt);}
2558 
2559  /// \brief Saves this object to a BufferedTransformation
2560  /// \param bt a BufferedTransformation object
2561  /// \details Use of DEREncode() changed to Save() at Issue 569.
2562  /// \deprecated for backwards compatibility, calls GetMaterial().Save(bt)
2563  void DEREncode(BufferedTransformation &bt) const
2564  {GetMaterial().Save(bt);}
2565 #endif
2566 };
2567 
2568 /// \brief Interface for asymmetric algorithms using public keys
2569 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
2570 {
2571 public:
2572  virtual ~PublicKeyAlgorithm() {}
2573 
2574  // VC60 workaround: no co-variant return type
2575 
2576  /// \brief Retrieves a reference to a Public Key
2577  /// \return a reference to the public key
2579  {return AccessPublicKey();}
2580  /// \brief Retrieves a reference to a Public Key
2581  /// \return a const reference the public key
2582  const CryptoMaterial & GetMaterial() const
2583  {return GetPublicKey();}
2584 
2585  /// \brief Retrieves a reference to a Public Key
2586  /// \return a reference to the public key
2587  virtual PublicKey & AccessPublicKey() =0;
2588  /// \brief Retrieves a reference to a Public Key
2589  /// \return a const reference the public key
2590  virtual const PublicKey & GetPublicKey() const
2591  {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
2592 };
2593 
2594 /// \brief Interface for asymmetric algorithms using private keys
2595 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
2596 {
2597 public:
2598  virtual ~PrivateKeyAlgorithm() {}
2599 
2600  /// \brief Retrieves a reference to a Private Key
2601  /// \return a reference the private key
2602  CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
2603  /// \brief Retrieves a reference to a Private Key
2604  /// \return a const reference the private key
2605  const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
2606 
2607  /// \brief Retrieves a reference to a Private Key
2608  /// \return a reference the private key
2609  virtual PrivateKey & AccessPrivateKey() =0;
2610  /// \brief Retrieves a reference to a Private Key
2611  /// \return a const reference the private key
2612  virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
2613 };
2614 
2615 /// \brief Interface for key agreement algorithms
2616 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
2617 {
2618 public:
2619  virtual ~KeyAgreementAlgorithm() {}
2620 
2621  /// \brief Retrieves a reference to Crypto Parameters
2622  /// \return a reference the crypto parameters
2623  CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
2624  /// \brief Retrieves a reference to Crypto Parameters
2625  /// \return a const reference the crypto parameters
2626  const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
2627 
2628  /// \brief Retrieves a reference to Crypto Parameters
2629  /// \return a reference the crypto parameters
2630  virtual CryptoParameters & AccessCryptoParameters() =0;
2631  /// \brief Retrieves a reference to Crypto Parameters
2632  /// \return a const reference the crypto parameters
2633  virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
2634 };
2635 
2636 /// \brief Interface for public-key encryptors and decryptors
2637 /// \details This class provides an interface common to encryptors and decryptors
2638 /// for querying their plaintext and ciphertext lengths.
2639 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
2640 {
2641 public:
2642  virtual ~PK_CryptoSystem() {}
2643 
2644  /// \brief Provides the maximum length of plaintext for a given ciphertext length
2645  /// \return the maximum size of the plaintext, in bytes
2646  /// \details This function returns 0 if ciphertextLength is not valid (too long or too short).
2647  virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
2648 
2649  /// \brief Calculate the length of ciphertext given length of plaintext
2650  /// \return the maximum size of the ciphertext, in bytes
2651  /// \details This function returns 0 if plaintextLength is not valid (too long).
2652  virtual size_t CiphertextLength(size_t plaintextLength) const =0;
2653 
2654  /// \brief Determines whether this object supports the use of a named parameter
2655  /// \param name the name of the parameter
2656  /// \return true if the parameter name is supported, false otherwise
2657  /// \details Some possible parameter names: EncodingParameters(), KeyDerivationParameters()
2658  /// and others Parameters listed in argnames.h
2659  virtual bool ParameterSupported(const char *name) const =0;
2660 
2661  /// \brief Provides the fixed ciphertext length, if one exists
2662  /// \return the fixed ciphertext length if one exists, otherwise 0
2663  /// \details "Fixed" here means length of ciphertext does not depend on length of plaintext.
2664  /// In this case, it usually does depend on the key length.
2665  virtual size_t FixedCiphertextLength() const {return 0;}
2666 
2667  /// \brief Provides the maximum plaintext length given a fixed ciphertext length
2668  /// \return maximum plaintext length given the fixed ciphertext length, if one exists,
2669  /// otherwise return 0.
2670  /// \details FixedMaxPlaintextLength(0 returns the maximum plaintext length given the fixed ciphertext
2671  /// length, if one exists, otherwise return 0.
2672  virtual size_t FixedMaxPlaintextLength() const {return 0;}
2673 };
2674 
2675 /// \brief Interface for public-key encryptors
2676 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
2677 {
2678 public:
2679  /// \brief Exception thrown when trying to encrypt plaintext of invalid length
2680  class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
2681  {
2682  public:
2683  InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
2684  };
2685 
2686  /// \brief Encrypt a byte string
2687  /// \param rng a RandomNumberGenerator derived class
2688  /// \param plaintext the plaintext byte buffer
2689  /// \param plaintextLength the size of the plaintext byte buffer
2690  /// \param ciphertext a byte buffer to hold the encrypted string
2691  /// \param parameters a set of NameValuePairs to initialize this object
2692  /// \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
2693  /// \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
2694  /// byte buffer is large enough.
2695  /// \sa PK_Decryptor
2696  virtual void Encrypt(RandomNumberGenerator &rng,
2697  const byte *plaintext, size_t plaintextLength,
2698  byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2699 
2700  /// \brief Create a new encryption filter
2701  /// \param rng a RandomNumberGenerator derived class
2702  /// \param attachment an attached transformation
2703  /// \param parameters a set of NameValuePairs to initialize this object
2704  /// \details \p attachment can be \p NULL. The caller is responsible for deleting the returned pointer.
2705  /// Encoding parameters should be passed in the "EP" channel.
2706  virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
2707  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2708 };
2709 
2710 /// \brief Interface for public-key decryptors
2711 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
2712 {
2713 public:
2714  virtual ~PK_Decryptor() {}
2715 
2716  /// \brief Decrypt a byte string
2717  /// \param rng a RandomNumberGenerator derived class
2718  /// \param ciphertext the encrypted byte buffer
2719  /// \param ciphertextLength the size of the encrypted byte buffer
2720  /// \param plaintext a byte buffer to hold the decrypted string
2721  /// \param parameters a set of NameValuePairs to initialize this object
2722  /// \return the result of the decryption operation
2723  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2724  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2725  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2726  /// is undefined.
2727  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2728  /// byte buffer is large enough
2729  /// \sa PK_Encryptor
2730  virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
2731  const byte *ciphertext, size_t ciphertextLength,
2732  byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2733 
2734  /// \brief Create a new decryption filter
2735  /// \param rng a RandomNumberGenerator derived class
2736  /// \param attachment an attached transformation
2737  /// \param parameters a set of NameValuePairs to initialize this object
2738  /// \return the newly created decryption filter
2739  /// \note the caller is responsible for deleting the returned pointer
2740  virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
2741  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2742 
2743  /// \brief Decrypt a fixed size ciphertext
2744  /// \param rng a RandomNumberGenerator derived class
2745  /// \param ciphertext the encrypted byte buffer
2746  /// \param plaintext a byte buffer to hold the decrypted string
2747  /// \param parameters a set of NameValuePairs to initialize this object
2748  /// \return the result of the decryption operation
2749  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2750  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2751  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2752  /// is undefined.
2753  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2754  /// byte buffer is large enough
2755  /// \sa PK_Encryptor
2756  DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
2757  {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
2758 };
2759 
2760 /// \brief Interface for public-key signers and verifiers
2761 /// \details This class provides an interface common to signers and verifiers for querying scheme properties
2762 /// \sa DL_SignatureSchemeBase, TF_SignatureSchemeBase, DL_SignerBase, TF_SignerBase
2763 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
2764 {
2765 public:
2766  /// \brief Exception throw when the private or public key has a length that can't be used
2767  /// \details InvalidKeyLength() may be thrown by any function in this class if the private
2768  /// or public key has a length that can't be used
2769  class CRYPTOPP_DLL InvalidKeyLength : public Exception
2770  {
2771  public:
2772  InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
2773  };
2774 
2775  /// \brief Exception throw when the private or public key is too short to sign or verify
2776  /// \details KeyTooShort() may be thrown by any function in this class if the private or public
2777  /// key is too short to sign or verify anything
2778  class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
2779  {
2780  public:
2781  KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
2782  };
2783 
2784  virtual ~PK_SignatureScheme() {}
2785 
2786  /// \brief Provides the signature length if it only depends on the key
2787  /// \return the signature length if it only depends on the key, in bytes
2788  /// \details SignatureLength() returns the signature length if it only depends on the key, otherwise 0.
2789  virtual size_t SignatureLength() const =0;
2790 
2791  /// \brief Provides the maximum signature length produced given the length of the recoverable message part
2792  /// \param recoverablePartLength the length of the recoverable message part, in bytes
2793  /// \return the maximum signature length produced for a given length of recoverable message part, in bytes
2794  /// \details MaxSignatureLength() returns the maximum signature length produced given the length of the
2795  /// recoverable message part.
2796  virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
2797  {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
2798 
2799  /// \brief Provides the length of longest message that can be recovered
2800  /// \return the length of longest message that can be recovered, in bytes
2801  /// \details MaxRecoverableLength() returns the length of longest message that can be recovered, or 0 if
2802  /// this signature scheme does not support message recovery.
2803  virtual size_t MaxRecoverableLength() const =0;
2804 
2805  /// \brief Provides the length of longest message that can be recovered from a signature of given length
2806  /// \param signatureLength the length of the signature, in bytes
2807  /// \return the length of longest message that can be recovered from a signature of given length, in bytes
2808  /// \details MaxRecoverableLengthFromSignatureLength() returns the length of longest message that can be
2809  /// recovered from a signature of given length, or 0 if this signature scheme does not support message
2810  /// recovery.
2811  virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
2812 
2813  /// \brief Determines whether a signature scheme requires a random number generator
2814  /// \return true if the signature scheme requires a RandomNumberGenerator() to sign
2815  /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take
2816  /// RandomNumberGenerator().
2817  virtual bool IsProbabilistic() const =0;
2818 
2819  /// \brief Determines whether the non-recoverable message part can be signed
2820  /// \return true if the non-recoverable message part can be signed
2821  virtual bool AllowNonrecoverablePart() const =0;
2822 
2823  /// \brief Determines whether the signature must be input before the message
2824  /// \return true if the signature must be input before the message during verifcation
2825  /// \details if SignatureUpfront() returns true, then you must input the signature before the message
2826  /// during verification. Otherwise you can input the signature at anytime.
2827  virtual bool SignatureUpfront() const {return false;}
2828 
2829  /// \brief Determines whether the recoverable part must be input before the non-recoverable part
2830  /// \return true if the recoverable part must be input before the non-recoverable part during signing
2831  /// \details RecoverablePartFirst() determines whether you must input the recoverable part before the
2832  /// non-recoverable part during signing
2833  virtual bool RecoverablePartFirst() const =0;
2834 };
2835 
2836 /// \brief Interface for accumulating messages to be signed or verified
2837 /// \details Only Update() should be called from the PK_MessageAccumulator() class. No other functions
2838 /// inherited from HashTransformation, like DigestSize() and TruncatedFinal(), should be called.
2839 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
2840 {
2841 public:
2842  /// \warning DigestSize() should not be called on PK_MessageAccumulator
2843  unsigned int DigestSize() const
2844  {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
2845 
2846  /// \warning TruncatedFinal() should not be called on PK_MessageAccumulator
2847  void TruncatedFinal(byte *digest, size_t digestSize)
2848  {
2849  CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
2850  throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
2851  }
2852 };
2853 
2854 /// \brief Interface for public-key signers
2855 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
2856 {
2857 public:
2858  virtual ~PK_Signer() {}
2859 
2860  /// \brief Create a new HashTransformation to accumulate the message to be signed
2861  /// \param rng a RandomNumberGenerator derived class
2862  /// \return a pointer to a PK_MessageAccumulator
2863  /// \details NewSignatureAccumulator() can be used with all signing methods. Sign() will autimatically delete the
2864  /// accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2865  virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
2866 
2867  /// \brief Input a recoverable message to an accumulator
2868  /// \param messageAccumulator a reference to a PK_MessageAccumulator
2869  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2870  /// \param recoverableMessageLength the size of the recoverable message part
2871  virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
2872 
2873  /// \brief Sign and delete the messageAccumulator
2874  /// \param rng a RandomNumberGenerator derived class
2875  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2876  /// \param signature a block of bytes for the signature
2877  /// \return actual signature length
2878  /// \details Sign() deletes the messageAccumulator, even if an exception is thrown.
2879  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2880  virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
2881 
2882  /// \brief Sign and restart messageAccumulator
2883  /// \param rng a RandomNumberGenerator derived class
2884  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2885  /// \param signature a block of bytes for the signature
2886  /// \param restart flag indicating whether the messageAccumulator should be restarted
2887  /// \return actual signature length
2888  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2889  virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
2890 
2891  /// \brief Sign a message
2892  /// \param rng a RandomNumberGenerator derived class
2893  /// \param message a pointer to the message
2894  /// \param messageLen the size of the message to be signed
2895  /// \param signature a block of bytes for the signature
2896  /// \return actual signature length
2897  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2898  virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
2899 
2900  /// \brief Sign a recoverable message
2901  /// \param rng a RandomNumberGenerator derived class
2902  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2903  /// \param recoverableMessageLength the size of the recoverable message part
2904  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2905  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2906  /// \param signature a block of bytes for the signature
2907  /// \return actual signature length
2908  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength(recoverableMessageLength)</tt>
2909  virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
2910  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
2911 };
2912 
2913 /// \brief Interface for public-key signature verifiers
2914 /// \details The Recover* functions throw NotImplemented if the signature scheme does not support
2915 /// message recovery.
2916 /// \details The Verify* functions throw InvalidDataFormat if the scheme does support message
2917 /// recovery and the signature contains a non-empty recoverable message part. The
2918 /// Recover* functions should be used in that case.
2919 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
2920 {
2921 public:
2922  virtual ~PK_Verifier() {}
2923 
2924  /// \brief Create a new HashTransformation to accumulate the message to be verified
2925  /// \return a pointer to a PK_MessageAccumulator
2926  /// \details NewVerificationAccumulator() can be used with all verification methods. Verify() will autimatically delete
2927  /// the accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2928  virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
2929 
2930  /// \brief Input signature into a message accumulator
2931  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2932  /// \param signature the signature on the message
2933  /// \param signatureLength the size of the signature
2934  virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
2935 
2936  /// \brief Check whether messageAccumulator contains a valid signature and message
2937  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2938  /// \return true if the signature is valid, false otherwise
2939  /// \details Verify() deletes the messageAccumulator, even if an exception is thrown.
2940  virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
2941 
2942  /// \brief Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
2943  /// \param messageAccumulator a reference to a PK_MessageAccumulator derived class
2944  /// \return true if the signature is valid, false otherwise
2945  /// \details VerifyAndRestart() restarts the messageAccumulator
2946  virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
2947 
2948  /// \brief Check whether input signature is a valid signature for input message
2949  /// \param message a pointer to the message to be verified
2950  /// \param messageLen the size of the message
2951  /// \param signature a pointer to the signature over the message
2952  /// \param signatureLen the size of the signature
2953  /// \return true if the signature is valid, false otherwise
2954  virtual bool VerifyMessage(const byte *message, size_t messageLen,
2955  const byte *signature, size_t signatureLen) const;
2956 
2957  /// \brief Recover a message from its signature
2958  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2959  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2960  /// \return the result of the verification operation
2961  /// \details Recover() deletes the messageAccumulator, even if an exception is thrown.
2962  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2963  virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
2964 
2965  /// \brief Recover a message from its signature
2966  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2967  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2968  /// \return the result of the verification operation
2969  /// \details RecoverAndRestart() restarts the messageAccumulator
2970  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2971  virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
2972 
2973  /// \brief Recover a message from its signature
2974  /// \param recoveredMessage a pointer for the recovered message
2975  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2976  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2977  /// \param signature the signature on the message
2978  /// \param signatureLength the size of the signature
2979  /// \return the result of the verification operation
2980  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2981  virtual DecodingResult RecoverMessage(byte *recoveredMessage,
2982  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
2983  const byte *signature, size_t signatureLength) const;
2984 };
2985 
2986 /// \brief Interface for domains of simple key agreement protocols
2987 /// \details A key agreement domain is a set of parameters that must be shared
2988 /// by two parties in a key agreement protocol, along with the algorithms
2989 /// for generating key pairs and deriving agreed values.
2990 /// \since Crypto++ 3.0
2991 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
2992 {
2993 public:
2994  virtual ~SimpleKeyAgreementDomain() {}
2995 
2996  /// \brief Provides the size of the agreed value
2997  /// \return size of agreed value produced in this domain
2998  virtual unsigned int AgreedValueLength() const =0;
2999 
3000  /// \brief Provides the size of the private key
3001  /// \return size of private keys in this domain
3002  virtual unsigned int PrivateKeyLength() const =0;
3003 
3004  /// \brief Provides the size of the public key
3005  /// \return size of public keys in this domain
3006  virtual unsigned int PublicKeyLength() const =0;
3007 
3008  /// \brief Generate private key in this domain
3009  /// \param rng a RandomNumberGenerator derived class
3010  /// \param privateKey a byte buffer for the generated private key in this domain
3011  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3012  virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3013 
3014  /// \brief Generate a public key from a private key in this domain
3015  /// \param rng a RandomNumberGenerator derived class
3016  /// \param privateKey a byte buffer with the previously generated private key
3017  /// \param publicKey a byte buffer for the generated public key in this domain
3018  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
3019  virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3020 
3021  /// \brief Generate a private/public key pair
3022  /// \param rng a RandomNumberGenerator derived class
3023  /// \param privateKey a byte buffer for the generated private key in this domain
3024  /// \param publicKey a byte buffer for the generated public key in this domain
3025  /// \details GenerateKeyPair() is equivalent to calling GeneratePrivateKey() and then GeneratePublicKey().
3026  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3027  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
3028  virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3029 
3030  /// \brief Derive agreed value
3031  /// \param agreedValue a byte buffer for the shared secret
3032  /// \param privateKey a byte buffer with your private key in this domain
3033  /// \param otherPublicKey a byte buffer with the other party's public key in this domain
3034  /// \param validateOtherPublicKey a flag indicating if the other party's public key should be validated
3035  /// \return true upon success, false in case of failure
3036  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3037  /// \details The other party's public key is validated by default. If you have previously validated the
3038  /// static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3039  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3040  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
3041  /// \pre <tt>COUNTOF(otherPublicKey) == PublicKeyLength()</tt>
3042  virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
3043 };
3044 
3045 /// \brief Interface for domains of authenticated key agreement protocols
3046 /// \details In an authenticated key agreement protocol, each party has two
3047 /// key pairs. The long-lived key pair is called the static key pair,
3048 /// and the short-lived key pair is called the ephemeral key pair.
3049 /// \since Crypto++ 3.0
3050 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3051 {
3052 public:
3053  virtual ~AuthenticatedKeyAgreementDomain() {}
3054 
3055  /// \brief Provides the size of the agreed value
3056  /// \return size of agreed value produced in this domain
3057  virtual unsigned int AgreedValueLength() const =0;
3058 
3059  /// \brief Provides the size of the static private key
3060  /// \return size of static private keys in this domain
3061  virtual unsigned int StaticPrivateKeyLength() const =0;
3062 
3063  /// \brief Provides the size of the static public key
3064  /// \return size of static public keys in this domain
3065  virtual unsigned int StaticPublicKeyLength() const =0;
3066 
3067  /// \brief Generate static private key in this domain
3068  /// \param rng a RandomNumberGenerator derived class
3069  /// \param privateKey a byte buffer for the generated private key in this domain
3070  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3071  virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3072 
3073  /// \brief Generate a static public key from a private key in this domain
3074  /// \param rng a RandomNumberGenerator derived class
3075  /// \param privateKey a byte buffer with the previously generated private key
3076  /// \param publicKey a byte buffer for the generated public key in this domain
3077  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3078  virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3079 
3080  /// \brief Generate a static private/public key pair
3081  /// \param rng a RandomNumberGenerator derived class
3082  /// \param privateKey a byte buffer for the generated private key in this domain
3083  /// \param publicKey a byte buffer for the generated public key in this domain
3084  /// \details GenerateStaticKeyPair() is equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey().
3085  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
3086  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
3087  virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3088 
3089  /// \brief Provides the size of ephemeral private key
3090  /// \return the size of ephemeral private key in this domain
3091  virtual unsigned int EphemeralPrivateKeyLength() const =0;
3092 
3093  /// \brief Provides the size of ephemeral public key
3094  /// \return the size of ephemeral public key in this domain
3095  virtual unsigned int EphemeralPublicKeyLength() const =0;
3096 
3097  /// \brief Generate ephemeral private key
3098  /// \param rng a RandomNumberGenerator derived class
3099  /// \param privateKey a byte buffer for the generated private key in this domain
3100  /// \pre <tt>COUNTOF(privateKey) == PrivateEphemeralKeyLength()</tt>
3101  virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3102 
3103  /// \brief Generate ephemeral public key
3104  /// \param rng a RandomNumberGenerator derived class
3105  /// \param privateKey a byte buffer for the generated private key in this domain
3106  /// \param publicKey a byte buffer for the generated public key in this domain
3107  /// \pre <tt>COUNTOF(publicKey) == PublicEphemeralKeyLength()</tt>
3108  virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3109 
3110  /// \brief Generate private/public key pair
3111  /// \param rng a RandomNumberGenerator derived class
3112  /// \param privateKey a byte buffer for the generated private key in this domain
3113  /// \param publicKey a byte buffer for the generated public key in this domain
3114  /// \details GenerateEphemeralKeyPair() is equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey()
3115  virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3116 
3117  /// \brief Derive agreed value
3118  /// \param agreedValue a byte buffer for the shared secret
3119  /// \param staticPrivateKey a byte buffer with your static private key in this domain
3120  /// \param ephemeralPrivateKey a byte buffer with your ephemeral private key in this domain
3121  /// \param staticOtherPublicKey a byte buffer with the other party's static public key in this domain
3122  /// \param ephemeralOtherPublicKey a byte buffer with the other party's ephemeral public key in this domain
3123  /// \param validateStaticOtherPublicKey a flag indicating if the other party's public key should be validated
3124  /// \return true upon success, false in case of failure
3125  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
3126  /// \details The other party's ephemeral public key is validated by default. If you have previously validated
3127  /// the static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3128  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3129  /// \pre <tt>COUNTOF(staticPrivateKey) == StaticPrivateKeyLength()</tt>
3130  /// \pre <tt>COUNTOF(ephemeralPrivateKey) == EphemeralPrivateKeyLength()</tt>
3131  /// \pre <tt>COUNTOF(staticOtherPublicKey) == StaticPublicKeyLength()</tt>
3132  /// \pre <tt>COUNTOF(ephemeralOtherPublicKey) == EphemeralPublicKeyLength()</tt>
3133  virtual bool Agree(byte *agreedValue,
3134  const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
3135  const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
3136  bool validateStaticOtherPublicKey=true) const =0;
3137 };
3138 
3139 // interface for password authenticated key agreement protocols, not implemented yet
3140 #if 0
3141 /// \brief Interface for protocol sessions
3142 /*! The methods should be called in the following order:
3143 
3144  InitializeSession(rng, parameters); // or call initialize method in derived class
3145  while (true)
3146  {
3147  if (OutgoingMessageAvailable())
3148  {
3149  length = GetOutgoingMessageLength();
3150  GetOutgoingMessage(message);
3151  ; // send outgoing message
3152  }
3153 
3154  if (LastMessageProcessed())
3155  break;
3156 
3157  ; // receive incoming message
3158  ProcessIncomingMessage(message);
3159  }
3160  ; // call methods in derived class to obtain result of protocol session
3161 */
3162 class ProtocolSession
3163 {
3164 public:
3165  /// Exception thrown when an invalid protocol message is processed
3166  class ProtocolError : public Exception
3167  {
3168  public:
3169  ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
3170  };
3171 
3172  /// Exception thrown when a function is called unexpectedly
3173  /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
3174  class UnexpectedMethodCall : public Exception
3175  {
3176  public:
3177  UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
3178  };
3179 
3180  virtual ~ProtocolSession() {}
3181 
3182  ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {}
3183 
3184  virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
3185 
3186  bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
3187  void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
3188 
3189  bool HasValidState() const {return m_validState;}
3190 
3191  virtual bool OutgoingMessageAvailable() const =0;
3192  virtual unsigned int GetOutgoingMessageLength() const =0;
3193  virtual void GetOutgoingMessage(byte *message) =0;
3194 
3195  virtual bool LastMessageProcessed() const =0;
3196  virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
3197 
3198 protected:
3199  void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
3200  void CheckAndHandleInvalidState() const;
3201  void SetValidState(bool valid) {m_validState = valid;}
3202 
3203  RandomNumberGenerator *m_rng;
3204 
3205 private:
3206  bool m_throwOnProtocolError, m_validState;
3207 };
3208 
3209 class KeyAgreementSession : public ProtocolSession
3210 {
3211 public:
3212  virtual ~KeyAgreementSession() {}
3213 
3214  virtual unsigned int GetAgreedValueLength() const =0;
3215  virtual void GetAgreedValue(byte *agreedValue) const =0;
3216 };
3217 
3218 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
3219 {
3220 public:
3221  virtual ~PasswordAuthenticatedKeyAgreementSession() {}
3222 
3223  void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
3224  const byte *myId, unsigned int myIdLength,
3225  const byte *counterPartyId, unsigned int counterPartyIdLength,
3226  const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
3227 };
3228 
3229 /// \brief Password based key agreement domain
3230 /// \since Crypto++ 3.0
3231 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3232 {
3233 public:
3234  virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
3235 
3236  /// return whether the domain parameters stored in this object are valid
3237  virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
3238  {return GetCryptoParameters().Validate(rng, 2);}
3239 
3240  virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
3241  virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
3242 
3243  enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
3244 
3245  virtual bool IsValidRole(unsigned int role) =0;
3246  virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
3247 };
3248 #endif
3249 
3250 /// \brief Exception thrown when an ASN.1 BER decoing error is encountered
3251 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
3252 {
3253 public:
3254  BERDecodeErr() : InvalidArgument("BER decode error") {}
3255  BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
3256 };
3257 
3258 /// \brief Interface for encoding and decoding ASN1 objects
3259 /// \details Each class that derives from ASN1Object should provide a serialization format
3260 /// that controls subobject layout. Most of the time the serialization format is
3261 /// taken from a standard, like P1363 or an RFC.
3262 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
3263 {
3264 public:
3265  virtual ~ASN1Object() {}
3266 
3267  /// \brief Decode this object from a BufferedTransformation
3268  /// \param bt BufferedTransformation object
3269  /// \details Uses Basic Encoding Rules (BER)
3270  virtual void BERDecode(BufferedTransformation &bt) =0;
3271 
3272  /// \brief Encode this object into a BufferedTransformation
3273  /// \param bt BufferedTransformation object
3274  /// \details Uses Distinguished Encoding Rules (DER)
3275  virtual void DEREncode(BufferedTransformation &bt) const =0;
3276 
3277  /// \brief Encode this object into a BufferedTransformation
3278  /// \param bt BufferedTransformation object
3279  /// \details Uses Basic Encoding Rules (BER).
3280  /// \details This may be useful if DEREncode() would be too inefficient.
3281  virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
3282 };
3283 
3284 /// \brief Specifies the build-time version of the library
3285 /// \return integer representing the build-time version
3286 /// \details LibraryVersion can help detect inadvertent mixing and matching of library
3287 /// versions. When using Crypto++ distributed by a third party, LibraryVersion()
3288 /// records the version of the shared object that was built by the third party.
3289 /// The LibraryVersion() record resides in <tt>cryptlib.o</tt> on Unix compatibles
3290 /// and <tt>cryptlib.obj</tt> on Windows. It does not change when an app links
3291 /// to the library.
3292 /// \details LibraryVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3293 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3294 /// the library version is 5.7 or above. If it is missing, then the library version is
3295 /// 5.6.5 or below.
3296 /// \details The function could be used as shown below.
3297 /// <pre> if (LibraryVersion() != HeaderVersion())
3298 /// {
3299 /// cout << "Potential version mismatch" << endl;
3300 ///
3301 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3302 /// const int lmin = (LibraryVersion() / 10U) % 10;
3303 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3304 /// const int hmin = (HeaderVersion() / 10U) % 10;
3305 ///
3306 /// if(lmaj != hmaj)
3307 /// cout << "Major version mismatch" << endl;
3308 /// else if(lmin != hmin)
3309 /// cout << "Minor version mismatch" << endl;
3310 /// }
3311 /// </pre>
3312 /// \sa HeaderVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3313 /// \since Crypto++ 6.0
3314 extern "C" {
3315  int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT);
3316 } // C linkage
3317 
3318 /// \brief Specifies the runtime version of the library
3319 /// \return integer representing the runtime version
3320 /// \details HeaderVersion() can help detect inadvertent mixing and matching of library
3321 /// versions. When using Crypto++ distributed by a third party, HeaderVersion()
3322 /// records the version of the headers used by the app when the app is compiled.
3323 /// \details HeaderVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3324 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3325 /// the library version is 5.7 or above. If it is missing, then the library version is
3326 /// 5.6.5 or below.
3327 /// \details The function could be used as shown below.
3328 /// <pre> if (LibraryVersion() != HeaderVersion())
3329 /// {
3330 /// cout << "Potential version mismatch" << endl;
3331 ///
3332 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3333 /// const int lmin = (LibraryVersion() / 10U) % 10;
3334 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3335 /// const int hmin = (HeaderVersion() / 10U) % 10;
3336 ///
3337 /// if(lmaj != hmaj)
3338 /// cout << "Major version mismatch" << endl;
3339 /// else if(lmin != hmin)
3340 /// cout << "Minor version mismatch" << endl;
3341 /// }
3342 /// </pre>
3343 /// \sa LibraryVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3344 /// \since Crypto++ 6.0
3345 extern "C" {
3346 inline int HeaderVersion()
3347 {
3348  return CRYPTOPP_VERSION;
3349 }
3350 } // C linkage
3351 
3352 NAMESPACE_END
3353 
3354 #if CRYPTOPP_MSC_VERSION
3355 # pragma warning(pop)
3356 #endif
3357 
3358 #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:3346
Exception thrown when invalid crypto material is detected.
Definition: cryptlib.h:2372
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition: cryptlib.h:2451
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:2538
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:2639
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:2406
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:2435
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition: cryptlib.h:2173
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:2626
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:2855
Interface for public-key encryptors.
Definition: cryptlib.h:2676
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:2756
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:2602
Interface for asymmetric algorithms using private keys.
Definition: cryptlib.h:2595
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:2087
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:2590
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:2519
virtual const BufferedTransformation * AttachedTransformation() const
Returns the object immediately attached to this object.
Definition: cryptlib.h:2326
Interface for cloning objects.
Definition: cryptlib.h:584
virtual size_t FixedCiphertextLength() const
Provides the fixed ciphertext length, if one exists.
Definition: cryptlib.h:2665
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:2005
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:2467
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:2472
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:2183
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:2991
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2605
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:2161
Returns a decoding results.
Definition: cryptlib.h:277
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: cryptlib.h:2460
Exception thrown when trying to encrypt plaintext of invalid length.
Definition: cryptlib.h:2680
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:1970
Interface for public-key decryptors.
Definition: cryptlib.h:2711
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:2778
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:2843
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:3262
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:2193
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:2164
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:2769
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:2090
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2320
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:2569
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:2763
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:2335
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:2839
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:2616
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:2578
void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
Transfer all bytes from this object to another BufferedTransformation.
Definition: cryptlib.h:2072
virtual const CryptoParameters & GetCryptoParameters() const
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2633
Interface for public-key signature verifiers.
Definition: cryptlib.h:2919
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:1992
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:2368
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:2529
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2499
Interface for password based key derivation functions.
Definition: cryptlib.h:1565
CryptoMaterial & AccessMaterial()
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2623
An invalid argument was detected.
Definition: cryptlib.h:167
Interface for crypto material.
Definition: cryptlib.h:2488
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:2524
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:1013
Interface for public keys.
Definition: cryptlib.h:2514
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:3050
virtual bool GetNextMessageSeries()
Retrieve the next message in a series.
Definition: cryptlib.h:2084
void TruncatedFinal(byte *digest, size_t digestSize)
Definition: cryptlib.h:2847
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:2050
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:3281
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:2418
virtual bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: cryptlib.h:2441
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:2243
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:2612
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2582
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:2796
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:2314
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:2827
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:2672
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition: cryptlib.h:2231
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:3251
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