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