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