Crypto++  7.0
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 7.0 API Reference
7 <dl>
8 <dt>Abstract Base Classes<dd>
9  cryptlib.h
10 <dt>Authenticated Encryption Modes<dd>
11  CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)"
12 <dt>Block Ciphers<dd>
13  \ref Rijndael "AES", ARIA, Weak::ARC4, Blowfish, BTEA, \ref CHAM128 "CHAM (64/128)", Camellia,
14  \ref CAST128 "CAST (128/256)", DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES",
15  \ref DES_XEX3 "DESX", GOST, HIGHT, IDEA, LEA, \ref LR "Luby-Rackoff", \ref Kalyna128 "Kalyna (128/256/512)",
16  MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent,
17  \ref SHACAL2 "SHACAL-2", SHARK, \ref SIMECK64 "SIMECK (32/64)" SKIPJACK, SM4, Square, TEA,
18  \ref ThreeWay "3-Way", \ref Threefish256 "Threefish (256/512/1024)", Twofish, XTEA
19 <dt>Stream Ciphers<dd>
20  \ref ChaCha "ChaCha (8/12/20)", \ref HC128 "HC-128/256", \ref Panama "Panama-LE", \ref Panama "Panama-BE",
21  Rabbit, Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20
22 <dt>Hash Functions<dd>
23  BLAKE2s, BLAKE2b, \ref Keccak "Keccak (F1600)", SHA1, SHA224, SHA256, SHA384, SHA512,
24  \ref SHA3 "SHA-3", SM3, Tiger, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, SipHash, Whirlpool,
25  Weak::MD2, Weak::MD4, Weak::MD5
26 <dt>Non-Cryptographic Checksums<dd>
27  CRC32, CRC32C, Adler32
28 <dt>Message Authentication Codes<dd>
29  BLAKE2b, BLAKE2s, CBC_MAC, CMAC, DMAC, \ref GCM "GCM (GMAC)", HMAC, Poly1305, TTMAC, VMAC
30 <dt>Random Number Generators<dd>
31  NullRNG, LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG,
32  NIST Hash_DRBG and HMAC_DRBG, \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)",
33  DARN, RDRAND, RDSEED
34 <dt>Key Derivation and Password-based Cryptography<dd>
35  HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)",
36  \ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)"
37 <dt>Public Key Cryptosystems<dd>
38  DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
39 <dt>Public Key Signature Schemes<dd>
40  DSA, DSA2, \ref ed25519 "Ed25519", GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO,
41  RabinSS, RWSS, ESIGN
42 <dt>Key Agreement<dd>
43  DH, DH2, \ref x25519 "X25519", \ref MQV_Domain "MQV", \ref HMQV_Domain "HMQV",
44  \ref FHMQV_Domain "FHMQV", ECDH, x25519, ECMQV, ECHMQV, ECFHMQV, XTR_DH
45 <dt>Algebraic Structures<dd>
46  Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
47  ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP
48 <dt>Secret Sharing and Information Dispersal<dd>
49  SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
50 <dt>Compression<dd>
51  Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
52 <dt>Input Source Classes<dd>
53  StringSource, ArraySource, VectorSource, FileSource, RandomNumberSource
54 <dt>Output Sink Classes<dd>
55  StringSinkTemplate, StringSink, VectorSink, ArraySink, FileSink, RandomNumberSink
56 <dt>Filter Wrappers<dd>
57  StreamTransformationFilter, AuthenticatedEncryptionFilter, AuthenticatedDecryptionFilter, HashFilter,
58  HashVerificationFilter, SignerFilter, SignatureVerificationFilter
59 <dt>Binary to Text Encoders and Decoders<dd>
60  HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder,
61  Base32Decoder
62 <dt>Wrappers for OS features<dd>
63  Timer, ThreadUserTimer
64 
65 </dl>
66 
67 <!--
68 
69 <dt>FIPS 140 validated cryptography<dd>
70  fips140.h
71 
72 In the DLL version of Crypto++, only the following implementation class are available.
73 <dl>
74 <dt>Block Ciphers<dd>
75  AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK
76 <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
77  \ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>",
78  \ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>"
79 <dt>Hash Functions<dd>
80  SHA1, SHA224, SHA256, SHA384, SHA512
81 <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
82  RSASS<PKCS1v15, H>, RSASS<PSS, H>, RSASS_ISO<H>, RWSS<P1363_EMSA2, H>, DSA, ECDSA<ECP, H>,
83  ECDSA<EC2N, H>
84 <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
85  HMAC<H>, CBC_MAC<DES_EDE2>, CBC_MAC<DES_EDE3>, GCM<AES>
86 <dt>Random Number Generators<dd>
87  DefaultAutoSeededRNG (AutoSeededX917RNG<AES>)
88 <dt>Key Agreement<dd>
89  DH, DH2
90 <dt>Public Key Cryptosystems<dd>
91  RSAES<OAEP<SHA1> >
92 </dl>
93 
94 -->
95 
96 <p>This reference manual is a work in progress. Some classes lack detailed descriptions.
97 <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
98 <p>Thanks to Ryan Phillips for providing the Doxygen configuration file
99 and getting us started on the manual.
100 */
101 
102 #ifndef CRYPTOPP_CRYPTLIB_H
103 #define CRYPTOPP_CRYPTLIB_H
104 
105 #include "config.h"
106 #include "stdcpp.h"
107 #include "trap.h"
108 
109 #if CRYPTOPP_MSC_VERSION
110 # pragma warning(push)
111 # pragma warning(disable: 4127 4189 4505 4702)
112 #endif
113 
114 NAMESPACE_BEGIN(CryptoPP)
115 
116 // forward declarations
117 class Integer;
120 
121 /// \brief Specifies a direction for a cipher to operate
122 /// \sa BlockTransformation::IsForwardTransformation(), BlockTransformation::IsPermutation(), BlockTransformation::GetCipherDirection()
123 enum CipherDir {
124  /// \brief the cipher is performing encryption
126  /// \brief the cipher is performing decryption
128 
129 /// \brief Represents infinite time
130 const unsigned long INFINITE_TIME = ULONG_MAX;
131 
132 // VC60 workaround: using enums as template parameters causes problems
133 /// \brief Converts an enumeration to a type suitable for use as a template parameter
134 template <typename ENUM_TYPE, int VALUE>
136 {
137  static ENUM_TYPE ToEnum() {return static_cast<ENUM_TYPE>(VALUE);}
138 };
139 
140 /// \brief Provides the byte ordering
141 /// \details Big-endian and little-endian modes are supported. Bi-endian and PDP-endian modes
142 /// are not supported.
143 enum ByteOrder {
144  /// \brief byte order is little-endian
146  /// \brief byte order is big-endian
148 
149 /// \brief Provides a constant for LittleEndian
151 /// \brief Provides a constant for BigEndian
153 
154 /// \brief Base class for all exceptions thrown by the library
155 /// \details All library exceptions directly or indirectly inherit from the Exception class.
156 /// The Exception class itself inherits from std::exception. The library does not use
157 /// std::runtime_error derived classes.
158 class CRYPTOPP_DLL Exception : public std::exception
159 {
160 public:
161  /// \enum ErrorType
162  /// \brief Error types or categories
163  enum ErrorType {
164  /// \brief A method was called which was not implemented
166  /// \brief An invalid argument was detected
168  /// \brief BufferedTransformation received a Flush(true) signal but can't flush buffers
170  /// \brief Data integerity check, such as CRC or MAC, failed
172  /// \brief Input data was received that did not conform to expected format
174  /// \brief Error reading from input device or writing to output device
176  /// \brief Some other error occurred not belonging to other categories
177  OTHER_ERROR
178  };
179 
180  virtual ~Exception() throw() {}
181 
182  /// \brief Construct a new Exception
183  explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
184 
185  /// \brief Retrieves a C-string describing the exception
186  const char *what() const throw() {return (m_what.c_str());}
187  /// \brief Retrieves a string describing the exception
188  const std::string &GetWhat() const {return m_what;}
189  /// \brief Sets the error string for the exception
190  void SetWhat(const std::string &s) {m_what = s;}
191  /// \brief Retrieves the error type for the exception
192  ErrorType GetErrorType() const {return m_errorType;}
193  /// \brief Sets the error type for the exceptions
194  void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
195 
196 private:
197  ErrorType m_errorType;
198  std::string m_what;
199 };
200 
201 /// \brief An invalid argument was detected
202 class CRYPTOPP_DLL InvalidArgument : public Exception
203 {
204 public:
205  explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
206 };
207 
208 /// \brief Input data was received that did not conform to expected format
209 class CRYPTOPP_DLL InvalidDataFormat : public Exception
210 {
211 public:
212  explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
213 };
214 
215 /// \brief A decryption filter encountered invalid ciphertext
216 class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
217 {
218 public:
219  explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
220 };
221 
222 /// \brief A method was called which was not implemented
223 class CRYPTOPP_DLL NotImplemented : public Exception
224 {
225 public:
226  explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
227 };
228 
229 /// \brief Flush(true) was called but it can't completely flush its buffers
230 class CRYPTOPP_DLL CannotFlush : public Exception
231 {
232 public:
233  explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
234 };
235 
236 /// \brief The operating system reported an error
237 class CRYPTOPP_DLL OS_Error : public Exception
238 {
239 public:
240  virtual ~OS_Error() throw() {}
241  OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
242  : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
243 
244  /// \brief Retrieve the operating system API that reported the error
245  const std::string & GetOperation() const {return m_operation;}
246  /// \brief Retrieve the error code returned by the operating system
247  int GetErrorCode() const {return m_errorCode;}
248 
249 protected:
250  std::string m_operation;
251  int m_errorCode;
252 };
253 
254 /// \brief Returns a decoding results
255 struct CRYPTOPP_DLL DecodingResult
256 {
257  /// \brief Constructs a DecodingResult
258  /// \details isValidCoding is initialized to false and messageLength is initialized to 0.
259  explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
260  /// \brief Constructs a DecodingResult
261  /// \param len the message length
262  /// \details isValidCoding is initialized to true.
263  explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
264 
265  /// \brief Compare two DecodingResult
266  /// \param rhs the other DecodingResult
267  /// \return true if both isValidCoding and messageLength are equal, false otherwise
268  bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
269  /// \brief Compare two DecodingResult
270  /// \param rhs the other DecodingResult
271  /// \return true if either isValidCoding or messageLength is \a not equal, false otherwise
272  /// \details Returns <tt>!operator==(rhs)</tt>.
273  bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
274 
275  /// \brief Flag to indicate the decoding is valid
277  /// \brief Recovered message length if isValidCoding is true, undefined otherwise
279 };
280 
281 /// \brief Interface for retrieving values given their names
282 /// \details This class is used to safely pass a variable number of arbitrarily typed arguments to functions
283 /// and to read values from keys and crypto parameters.
284 /// \details To obtain an object that implements NameValuePairs for the purpose of parameter
285 /// passing, use the MakeParameters() function.
286 /// \details To get a value from NameValuePairs, you need to know the name and the type of the value.
287 /// Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports.
288 /// then look at the Name namespace documentation to see what the type of each value is, or
289 /// alternatively, call GetIntValue() with the value name, and if the type is not int, a
290 /// ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object.
291 /// \sa NullNameValuePairs, g_nullNameValuePairs,
292 /// <A HREF="http://www.cryptopp.com/wiki/NameValuePairs">NameValuePairs</A> on the Crypto++ wiki
294 {
295 public:
296  virtual ~NameValuePairs() {}
297 
298  /// \brief Thrown when an unexpected type is encountered
299  /// \details Exception thrown when trying to retrieve a value using a different type than expected
300  class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
301  {
302  public:
303  /// \brief Construct a ValueTypeMismatch
304  /// \param name the name of the value
305  /// \param stored the \a actual type of the value stored
306  /// \param retrieving the \a presumed type of the value retrieved
307  ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
308  : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
309  , m_stored(stored), m_retrieving(retrieving) {}
310 
311  /// \brief Provides the stored type
312  /// \return the C++ mangled name of the type
313  const std::type_info & GetStoredTypeInfo() const {return m_stored;}
314 
315  /// \brief Provides the retrieveing type
316  /// \return the C++ mangled name of the type
317  const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
318 
319  private:
320  const std::type_info &m_stored;
321  const std::type_info &m_retrieving;
322  };
323 
324  /// \brief Get a copy of this object or subobject
325  /// \tparam T class or type
326  /// \param object reference to a variable that receives the value
327  template <class T>
328  bool GetThisObject(T &object) const
329  {
330  return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
331  }
332 
333  /// \brief Get a pointer to this object
334  /// \tparam T class or type
335  /// \param ptr reference to a pointer to a variable that receives the value
336  template <class T>
337  bool GetThisPointer(T *&ptr) const
338  {
339  return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr);
340  }
341 
342  /// \brief Get a named value
343  /// \tparam T class or type
344  /// \param name the name of the object or value to retrieve
345  /// \param value reference to a variable that receives the value
346  /// \returns true if the value was retrieved, false otherwise
347  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
348  /// GetRequiredParameter() and GetRequiredIntParameter()
349  template <class T>
350  bool GetValue(const char *name, T &value) const
351  {
352  return GetVoidValue(name, typeid(T), &value);
353  }
354 
355  /// \brief Get a named value
356  /// \tparam T class or type
357  /// \param name the name of the object or value to retrieve
358  /// \param defaultValue the default value of the class or type if it does not exist
359  /// \return the object or value
360  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
361  /// GetRequiredParameter() and GetRequiredIntParameter()
362  template <class T>
363  T GetValueWithDefault(const char *name, T defaultValue) const
364  {
365  T value;
366  bool result = GetValue(name, value);
367  // No assert... this recovers from failure
368  if (result) {return value;}
369  return defaultValue;
370  }
371 
372  /// \brief Get a list of value names that can be retrieved
373  /// \return a list of names available to retrieve
374  /// \details the items in the list are delimited with a colon.
375  CRYPTOPP_DLL std::string GetValueNames() const
376  {std::string result; GetValue("ValueNames", result); return result;}
377 
378  /// \brief Get a named value with type int
379  /// \param name the name of the value to retrieve
380  /// \param value the value retrieved upon success
381  /// \return true if an int value was retrieved, false otherwise
382  /// \details GetIntValue() is used to ensure we don't accidentally try to get an
383  /// unsigned int or some other type when we mean int (which is the most common case)
384  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
385  /// GetRequiredParameter() and GetRequiredIntParameter()
386  CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
387  {return GetValue(name, value);}
388 
389  /// \brief Get a named value with type int, with default
390  /// \param name the name of the value to retrieve
391  /// \param defaultValue the default value if the name does not exist
392  /// \return the value retrieved on success or the default value
393  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
394  /// GetRequiredParameter() and GetRequiredIntParameter()
395  CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
396  {return GetValueWithDefault(name, defaultValue);}
397 
398  /// \brief Get a named value with type word64
399  /// \param name the name of the value to retrieve
400  /// \param value the value retrieved upon success
401  /// \return true if an word64 value was retrieved, false otherwise
402  /// \sa GetValue(), GetValueWithDefault(), GetWord64ValueWithDefault(), GetIntValue(),
403  /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredIntParameter()
404  CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const
405  {return GetValue(name, value);}
406 
407  /// \brief Get a named value with type word64, with default
408  /// \param name the name of the value to retrieve
409  /// \param defaultValue the default value if the name does not exist
410  /// \return the value retrieved on success or the default value
411  /// \sa GetValue(), GetValueWithDefault(), GetWord64Value(), GetIntValue(),
412  /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredWord64Parameter()
413  CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
414  {return GetValueWithDefault(name, defaultValue);}
415 
416  /// \brief Ensures an expected name and type is present
417  /// \param name the name of the value
418  /// \param stored the type that was stored for the name
419  /// \param retrieving the type that is being retrieved for the name
420  /// \throws ValueTypeMismatch
421  /// \details ThrowIfTypeMismatch() effectively performs a type safety check.
422  /// stored and retrieving are C++ mangled names for the type.
423  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
424  /// GetRequiredParameter() and GetRequiredIntParameter()
425  CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
426  {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
427 
428  /// \brief Retrieves a required name/value pair
429  /// \tparam T class or type
430  /// \param className the name of the class
431  /// \param name the name of the value
432  /// \param value reference to a variable to receive the value
433  /// \throws InvalidArgument
434  /// \details GetRequiredParameter() throws InvalidArgument if the name
435  /// is not present or not of the expected type T.
436  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
437  /// GetRequiredParameter() and GetRequiredIntParameter()
438  template <class T>
439  void GetRequiredParameter(const char *className, const char *name, T &value) const
440  {
441  if (!GetValue(name, value))
442  throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
443  }
444 
445  /// \brief Retrieves a required name/value pair
446  /// \param className the name of the class
447  /// \param name the name of the value
448  /// \param value reference to a variable to receive the value
449  /// \throws InvalidArgument
450  /// \details GetRequiredParameter() throws InvalidArgument if the name
451  /// is not present or not of the expected type T.
452  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
453  /// GetRequiredParameter() and GetRequiredIntParameter()
454  CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
455  {
456  if (!GetIntValue(name, value))
457  throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
458  }
459 
460  /// \brief Get a named value
461  /// \param name the name of the object or value to retrieve
462  /// \param valueType reference to a variable that receives the value
463  /// \param pValue void pointer to a variable that receives the value
464  /// \returns true if the value was retrieved, false otherwise
465  /// \details GetVoidValue() retrieves the value of name if it exists.
466  /// \note GetVoidValue() is an internal function and should be implemented
467  /// by derived classes. Users should use one of the other functions instead.
468  /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
469  /// GetRequiredParameter() and GetRequiredIntParameter()
470  CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
471 };
472 
473 // Doxygen cannot handle initialization
474 #if CRYPTOPP_DOXYGEN_PROCESSING
475 /// \brief Default channel for BufferedTransformation
476 /// \details DEFAULT_CHANNEL is equal to an empty string
477 /// \details The definition for DEFAULT_CHANNEL is in <tt>cryptlib.cpp</tt>.
478 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
479 /// Initialization Order Fiasco</A>. If you experience a crash in
480 /// DEFAULT_CHANNEL where the string object is NULL, then you probably have
481 /// a global object using DEFAULT_CHANNEL before it has been constructed.
482 const std::string DEFAULT_CHANNEL;
483 
484 /// \brief Channel for additional authenticated data
485 /// \details AAD_CHANNEL is equal to "AAD"
486 /// \details The definition for AAD_CHANNEL is in <tt>cryptlib.cpp</tt>.
487 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
488 /// Initialization Order Fiasco</A>. If you experience a crash in
489 /// AAD_CHANNEL where the string object is NULL, then you probably have a
490 /// global object using AAD_CHANNEL before it has been constructed.
491 const std::string AAD_CHANNEL;
492 
493 /// \brief An empty set of name-value pairs
494 /// \details The definition for g_nullNameValuePairs is in <tt>cryptlib.cpp</tt>.
495 /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
496 /// Initialization Order Fiasco</A>. If you experience a crash in
497 /// g_nullNameValuePairs where the string object is NULL, then you probably
498 /// have a global object using g_nullNameValuePairs before it has been
499 /// constructed.
501 
502 #else
503 extern const std::string DEFAULT_CHANNEL;
504 extern const std::string AAD_CHANNEL;
506 #endif
507 
508 // Document additional name spaces which show up elsewhere in the sources.
509 #if CRYPTOPP_DOXYGEN_PROCESSING
510 /// \brief Namespace containing value name definitions.
511 /// \details Name is part of the CryptoPP namespace.
512 /// \details The semantics of value names, types are:
513 /// <pre>
514 /// ThisObject:ClassName (ClassName, copy of this object or a subobject)
515 /// ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
516 /// </pre>
517 DOCUMENTED_NAMESPACE_BEGIN(Name)
518 // more names defined in argnames.h
519 DOCUMENTED_NAMESPACE_END
520 
521 /// \brief Namespace containing weak and wounded algorithms.
522 /// \details Weak is part of the CryptoPP namespace. Schemes and algorithms are moved into Weak
523 /// when their security level is reduced to an unacceptable level by contemporary standards.
524 /// \details To use an algorithm in the Weak namespace, you must <tt>\c \#define
525 /// CRYPTOPP_ENABLE_NAMESPACE_WEAK 1</tt> before including a header for a weak or wounded
526 /// algorithm. For example:
527 /// <pre>
528 /// \c \#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
529 /// \c \#include <md5.h>
530 /// ...
531 /// CryptoPP::Weak::MD5 md5;
532 /// </pre>
533 DOCUMENTED_NAMESPACE_BEGIN(Weak)
534 // weak and wounded algorithms
535 DOCUMENTED_NAMESPACE_END
536 #endif
537 
538 /// \brief Namespace containing NaCl library functions
539 /// \details TweetNaCl is a compact and portable reimplementation of the NaCl library.
540 DOCUMENTED_NAMESPACE_BEGIN(NaCl)
541 // crypto_box, crypto_box_open, crypto_sign, and crypto_sign_open (and friends)
542 DOCUMENTED_NAMESPACE_END
543 
544 /// \brief Namespace containing testing and benchmark classes.
545 /// \details Source files for classes in the Test namespaces include
546 /// <tt>test.cpp</tt>, <tt>validat#.cpp</tt> and <tt>bench#.cpp</tt>.
547 DOCUMENTED_NAMESPACE_BEGIN(Test)
548 // testing and benchmark classes
549 DOCUMENTED_NAMESPACE_END
550 
551 // ********************************************************
552 
553 /// \brief Interface for cloning objects
554 /// \note this is \a not implemented by most classes
555 /// \sa ClonableImpl, NotCopyable
556 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
557 {
558 public:
559  virtual ~Clonable() {}
560 
561  /// \brief Copies this object
562  /// \return a copy of this object
563  /// \throws NotImplemented
564  /// \note this is \a not implemented by most classes
565  /// \sa NotCopyable
566  virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
567 };
568 
569 /// \brief Interface for all crypto algorithms
570 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
571 {
572 public:
573  virtual ~Algorithm() {}
574 
575  /// \brief Interface for all crypto algorithms
576  /// \param checkSelfTestStatus determines whether the object can proceed if the self
577  /// tests have not been run or failed.
578  /// \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
579  /// this constructor throws SelfTestFailure if the self test hasn't been run or fails.
580  /// \details FIPS 140-2 compliance is disabled by default. It is only used by certain
581  /// versions of the library when the library is built as a DLL on Windows. Also see
582  /// CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h.
583  Algorithm(bool checkSelfTestStatus = true);
584 
585  /// \brief Provides the name of this algorithm
586  /// \return the standard algorithm name
587  /// \details The standard algorithm name can be a name like <tt>AES</tt> or <tt>AES/GCM</tt>.
588  /// Some algorithms do not have standard names yet. For example, there is no standard
589  /// algorithm name for Shoup's ECIES.
590  /// \note AlgorithmName is not universally implemented yet.
591  virtual std::string AlgorithmName() const {return "unknown";}
592 
593  /// \brief Retrieve the provider of this algorithm
594  /// \return the algorithm provider
595  /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
596  /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
597  /// usually indicate a specialized implementation using instructions from a higher
598  /// instruction set architecture (ISA). Future labels may include external hardware
599  /// like a hardware security module (HSM).
600  /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
601  /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
602  /// instead of ASM.
603  /// \details Algorithms which combine different instructions or ISAs provide the
604  /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
605  /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
606  /// \note Provider is not universally implemented yet.
607  /// \since Crypto++ 7.1
608  virtual std::string AlgorithmProvider() const {return "C++";}
609 };
610 
611 /// \brief Interface for algorithms that take byte strings as keys
612 /// \sa FixedKeyLength(), VariableKeyLength(), SameKeyLengthAs(), SimpleKeyingInterfaceImpl()
613 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
614 {
615 public:
616  virtual ~SimpleKeyingInterface() {}
617 
618  /// \brief Returns smallest valid key length
619  /// \returns the minimum key length, in bytes
620  virtual size_t MinKeyLength() const =0;
621 
622  /// \brief Returns largest valid key length
623  /// \returns the maximum key length, in bytes
624  virtual size_t MaxKeyLength() const =0;
625 
626  /// \brief Returns default key length
627  /// \returns the default key length, in bytes
628  virtual size_t DefaultKeyLength() const =0;
629 
630  /// \brief Returns a valid key length for the algorithm
631  /// \param keylength the size of the key, in bytes
632  /// \returns the valid key length, in bytes
633  /// \details keylength is provided in bytes, not bits. If keylength is less than MIN_KEYLENGTH,
634  /// then the function returns MIN_KEYLENGTH. If keylength is greater than MAX_KEYLENGTH,
635  /// then the function returns MAX_KEYLENGTH. if If keylength is a multiple of KEYLENGTH_MULTIPLE,
636  /// then keylength is returned. Otherwise, the function returns a \a lower multiple of
637  /// KEYLENGTH_MULTIPLE.
638  virtual size_t GetValidKeyLength(size_t keylength) const =0;
639 
640  /// \brief Returns whether keylength is a valid key length
641  /// \param keylength the requested keylength
642  /// \return true if keylength is valid, false otherwise
643  /// \details Internally the function calls GetValidKeyLength()
644  virtual bool IsValidKeyLength(size_t keylength) const
645  {return keylength == GetValidKeyLength(keylength);}
646 
647  /// \brief Sets or reset the key of this object
648  /// \param key the key to use when keying the object
649  /// \param length the size of the key, in bytes
650  /// \param params additional initialization parameters to configure this object
651  virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
652 
653  /// \brief Sets or reset the key of this object
654  /// \param key the key to use when keying the object
655  /// \param length the size of the key, in bytes
656  /// \param rounds the number of rounds to apply the transformation function,
657  /// if applicable
658  /// \details SetKeyWithRounds() calls SetKey() with a NameValuePairs
659  /// object that only specifies rounds. rounds is an integer parameter,
660  /// and <tt>-1</tt> means use the default number of rounds.
661  void SetKeyWithRounds(const byte *key, size_t length, int rounds);
662 
663  /// \brief Sets or reset the key of this object
664  /// \param key the key to use when keying the object
665  /// \param length the size of the key, in bytes
666  /// \param iv the initialization vector to use when keying the object
667  /// \param ivLength the size of the iv, in bytes
668  /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs
669  /// that only specifies IV. The IV is a byte buffer with size ivLength.
670  /// ivLength is an integer parameter, and <tt>-1</tt> means use IVSize().
671  void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
672 
673  /// \brief Sets or reset the key of this object
674  /// \param key the key to use when keying the object
675  /// \param length the size of the key, in bytes
676  /// \param iv the initialization vector to use when keying the object
677  /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs() object
678  /// that only specifies iv. iv is a byte buffer, and it must have
679  /// a size IVSize().
680  void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
681  {SetKeyWithIV(key, length, iv, IVSize());}
682 
683  /// \brief Secure IVs requirements as enumerated values.
684  /// \details Provides secure IV requirements as a monotonically increasing enumerated values.
685  /// Requirements can be compared using less than (&lt;) and greater than (&gt;). For example,
686  /// <tt>UNIQUE_IV &lt; RANDOM_IV</tt> and <tt>UNPREDICTABLE_RANDOM_IV &gt; RANDOM_IV</tt>.
687  /// \details Objects that use SimpleKeyingInterface do not support an optional IV. That is,
688  /// an IV must be present or it must be absent. If you wish to support an optional IV then
689  /// provide two classes - one with an IV and one without an IV.
690  /// \sa IsResynchronizable(), CanUseRandomIVs(), CanUsePredictableIVs(), CanUseStructuredIVs()
692  /// \brief The IV must be unique
693  UNIQUE_IV = 0,
694  /// \brief The IV must be random and possibly predictable
696  /// \brief The IV must be random and unpredictable
698  /// \brief The IV is set by the object
700  /// \brief The object does not use an IV
701  NOT_RESYNCHRONIZABLE
702  };
703 
704  /// \brief Minimal requirement for secure IVs
705  /// \return the secure IV requirement of the algorithm
706  virtual IV_Requirement IVRequirement() const =0;
707 
708  /// \brief Determines if the object can be resynchronized
709  /// \return true if the object can be resynchronized (i.e. supports initialization vectors), false otherwise
710  /// \note If this function returns true, and no IV is passed to SetKey() and <tt>CanUseStructuredIVs()==true</tt>,
711  /// an IV of all 0's will be assumed.
712  bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
713 
714  /// \brief Determines if the object can use random IVs
715  /// \return true if the object can use random IVs (in addition to ones returned by GetNextIV), false otherwise
716  bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
717 
718  /// \brief Determines if the object can use random but possibly predictable IVs
719  /// \return true if the object can use random but possibly predictable IVs (in addition to ones returned by
720  /// GetNextIV), false otherwise
721  bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
722 
723  /// \brief Determines if the object can use structured IVs
724  /// \returns true if the object can use structured IVs, false otherwise
725  /// \details CanUseStructuredIVs() indicates whether the object can use structured IVs; for example a counter
726  /// (in addition to ones returned by GetNextIV).
727  bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
728 
729  /// \brief Returns length of the IV accepted by this object
730  /// \return the size of an IV, in bytes
731  /// \throws NotImplemented() if the object does not support resynchronization
732  /// \details The default implementation throws NotImplemented
733  virtual unsigned int IVSize() const
734  {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
735 
736  /// \brief Provides the default size of an IV
737  /// \return default length of IVs accepted by this object, in bytes
738  unsigned int DefaultIVLength() const {return IVSize();}
739 
740  /// \brief Provides the minimum size of an IV
741  /// \return minimal length of IVs accepted by this object, in bytes
742  /// \throws NotImplemented() if the object does not support resynchronization
743  virtual unsigned int MinIVLength() const {return IVSize();}
744 
745  /// \brief Provides the maximum size of an IV
746  /// \return maximal length of IVs accepted by this object, in bytes
747  /// \throws NotImplemented() if the object does not support resynchronization
748  virtual unsigned int MaxIVLength() const {return IVSize();}
749 
750  /// \brief Resynchronize with an IV
751  /// \param iv the initialization vector
752  /// \param ivLength the size of the initialization vector, in bytes
753  /// \details Resynchronize() resynchronizes with an IV provided by the caller. <tt>ivLength=-1</tt> means use IVSize().
754  /// \throws NotImplemented() if the object does not support resynchronization
755  virtual void Resynchronize(const byte *iv, int ivLength=-1) {
756  CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength);
757  throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");
758  }
759 
760  /// \brief Retrieves a secure IV for the next message
761  /// \param rng a RandomNumberGenerator to produce keying material
762  /// \param iv a block of bytes to receive the IV
763  /// \details The IV must be at least IVSize() in length.
764  /// \details This method should be called after you finish encrypting one message and are ready
765  /// to start the next one. After calling it, you must call SetKey() or Resynchronize().
766  /// before using this object again.
767  /// \details Internally, the base class implementation calls RandomNumberGenerator's GenerateBlock()
768  /// \note This method is not implemented on decryption objects.
769  virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
770 
771 protected:
772  /// \brief Returns the base class Algorithm
773  /// \return the base class Algorithm
774  virtual const Algorithm & GetAlgorithm() const =0;
775 
776  /// \brief Sets the key for this object without performing parameter validation
777  /// \param key a byte buffer used to key the cipher
778  /// \param length the length of the byte buffer
779  /// \param params additional parameters passed as NameValuePairs
780  /// \details key must be at least DEFAULT_KEYLENGTH in length.
781  virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
782 
783  /// \brief Validates the key length
784  /// \param length the size of the keying material, in bytes
785  /// \throws InvalidKeyLength if the key length is invalid
786  void ThrowIfInvalidKeyLength(size_t length);
787 
788  /// \brief Validates the object
789  /// \throws InvalidArgument if the IV is present
790  /// \details Internally, the default implementation calls IsResynchronizable() and throws
791  /// InvalidArgument if the function returns true.
792  /// \note called when no IV is passed
793  void ThrowIfResynchronizable();
794 
795  /// \brief Validates the IV
796  /// \param iv the IV with a length of IVSize, in bytes
797  /// \throws InvalidArgument on failure
798  /// \details Internally, the default implementation checks the iv. If iv is not NULL or nullptr,
799  /// then the function succeeds. If iv is NULL, then IVRequirement is checked against
800  /// UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then
801  /// then the function succeeds. Otherwise, an exception is thrown.
802  void ThrowIfInvalidIV(const byte *iv);
803 
804  /// \brief Validates the IV length
805  /// \param length the size of an IV, in bytes
806  /// \throws InvalidArgument if the IV length is invalid
807  size_t ThrowIfInvalidIVLength(int length);
808 
809  /// \brief Retrieves and validates the IV
810  /// \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter
811  /// \param size the length of the IV, in bytes
812  /// \return a pointer to the first byte of the IV
813  /// \throws InvalidArgument if the number of rounds are invalid
814  const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
815 
816  /// \brief Validates the key length
817  /// \param length the size of the keying material, in bytes
818  inline void AssertValidKeyLength(size_t length) const
819  {CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));}
820 };
821 
822 /// \brief Interface for the data processing part of block ciphers
823 /// \details Classes derived from BlockTransformation are block ciphers
824 /// in ECB mode (for example the DES::Encryption class), which are stateless.
825 /// These classes should not be used directly, but only in combination with
826 /// a mode class (see CipherModeDocumentation in modes.h).
827 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
828 {
829 public:
830  virtual ~BlockTransformation() {}
831 
832  /// \brief Encrypt or decrypt a block
833  /// \param inBlock the input message before processing
834  /// \param outBlock the output message after processing
835  /// \param xorBlock an optional XOR mask
836  /// \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock.
837  /// \details The size of the block is determined by the block cipher and its documentation. Use
838  /// BLOCKSIZE at compile time, or BlockSize() at runtime.
839  /// \note The message can be transformed in-place, or the buffers must \a not overlap
840  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
841  virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
842 
843  /// \brief Encrypt or decrypt a block
844  /// \param inBlock the input message before processing
845  /// \param outBlock the output message after processing
846  /// \details ProcessBlock encrypts or decrypts inBlock and write to outBlock.
847  /// \details The size of the block is determined by the block cipher and its documentation.
848  /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
849  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
850  /// \note The message can be transformed in-place, or the buffers must \a not overlap
851  void ProcessBlock(const byte *inBlock, byte *outBlock) const
852  {ProcessAndXorBlock(inBlock, NULLPTR, outBlock);}
853 
854  /// \brief Encrypt or decrypt a block in place
855  /// \param inoutBlock the input message before processing
856  /// \details ProcessBlock encrypts or decrypts inoutBlock in-place.
857  /// \details The size of the block is determined by the block cipher and its documentation.
858  /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
859  /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
860  void ProcessBlock(byte *inoutBlock) const
861  {ProcessAndXorBlock(inoutBlock, NULLPTR, inoutBlock);}
862 
863  /// Provides the block size of the cipher
864  /// \return the block size of the cipher, in bytes
865  virtual unsigned int BlockSize() const =0;
866 
867  /// \brief Provides input and output data alignment for optimal performance.
868  /// \return the input data alignment that provides optimal performance
869  /// \sa GetAlignment() and OptimalBlockSize()
870  virtual unsigned int OptimalDataAlignment() const;
871 
872  /// \brief Determines if the transformation is a permutation
873  /// \returns true if this is a permutation (i.e. there is an inverse transformation)
874  virtual bool IsPermutation() const {return true;}
875 
876  /// \brief Determines if the cipher is being operated in its forward direction
877  /// \returns true if DIR is ENCRYPTION, false otherwise
878  /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
879  virtual bool IsForwardTransformation() const =0;
880 
881  /// \brief Determines the number of blocks that can be processed in parallel
882  /// \return the number of blocks that can be processed in parallel, for bit-slicing implementations
883  /// \details Bit-slicing is often used to improve throughput and minimize timing attacks.
884  virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
885 
886  /// \brief Bit flags that control AdvancedProcessBlocks() behavior
888  /// \brief inBlock is a counter
889  BT_InBlockIsCounter=1,
890  /// \brief should not modify block pointers
891  BT_DontIncrementInOutPointers=2,
892  /// \brief Xor inputs before transformation
893  BT_XorInput=4,
894  /// \brief perform the transformation in reverse
895  BT_ReverseDirection=8,
896  /// \brief Allow parallel transformations
897  BT_AllowParallel=16};
898 
899  /// \brief Encrypt and xor multiple blocks using additional flags
900  /// \param inBlocks the input message before processing
901  /// \param xorBlocks an optional XOR mask
902  /// \param outBlocks the output message after processing
903  /// \param length the size of the blocks, in bytes
904  /// \param flags additional flags to control processing
905  /// \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags.
906  /// \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified.
907  virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
908 
909  /// \brief Provides the direction of the cipher
910  /// \return ENCRYPTION if IsForwardTransformation() is true, DECRYPTION otherwise
911  /// \sa IsForwardTransformation(), IsPermutation()
912  inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
913 };
914 
915 /// \brief Interface for the data processing portion of stream ciphers
916 /// \sa StreamTransformationFilter()
917 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
918 {
919 public:
920  virtual ~StreamTransformation() {}
921 
922  /// \brief Provides a reference to this object
923  /// \return A reference to this object
924  /// \details Useful for passing a temporary object to a function that takes a non-const reference
925  StreamTransformation& Ref() {return *this;}
926 
927  /// \brief Provides the mandatory block size of the cipher
928  /// \return The block size of the cipher if input must be processed in blocks, 1 otherwise
929  /// \details Stream ciphers and some block ciphers modes of operation return 1. Modes that
930  /// return 1 must be able to process a single byte at a time, like counter mode. If a
931  /// mode of operation or block cipher cannot stream then it must not return 1.
932  /// \details When filters operate the mode or cipher, ProcessData will be called with a
933  /// string of bytes that is determined by MandatoryBlockSize and OptimalBlockSize. When a
934  /// policy is set, like 16-byte strings for a 16-byte block cipher, the filter will buffer
935  /// bytes until the specified number of bytes is available to the object.
936  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
937  virtual unsigned int MandatoryBlockSize() const {return 1;}
938 
939  /// \brief Provides the input block size most efficient for this cipher
940  /// \return The input block size that is most efficient for the cipher
941  /// \details The base class implementation returns MandatoryBlockSize().
942  /// \note Optimal input length is
943  /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>.
944  virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
945 
946  /// \brief Provides the number of bytes used in the current block when processing at optimal block size.
947  /// \return the number of bytes used in the current block when processing at the optimal block size
948  virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
949 
950  /// \brief Provides input and output data alignment for optimal performance
951  /// \return the input data alignment that provides optimal performance
952  /// \sa GetAlignment() and OptimalBlockSize()
953  virtual unsigned int OptimalDataAlignment() const;
954 
955  /// \brief Encrypt or decrypt an array of bytes
956  /// \param outString the output byte buffer
957  /// \param inString the input byte buffer
958  /// \param length the size of the input and output byte buffers, in bytes
959  /// \details ProcessData is called with a string of bytes whose size depends on MandatoryBlockSize.
960  /// Either <tt>inString == outString</tt>, or they must not overlap.
961  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
962  virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
963 
964  /// \brief Encrypt or decrypt the last block of data
965  /// \param outString the output byte buffer
966  /// \param outLength the size of the output byte buffer, in bytes
967  /// \param inString the input byte buffer
968  /// \param inLength the size of the input byte buffer, in bytes
969  /// \returns the number of bytes used in outString
970  /// \details ProcessLastBlock is used when the last block of data is special and requires handling
971  /// by the cipher. The current implementation provides an output buffer with a size
972  /// <tt>inLength+2*MandatoryBlockSize()</tt>. The return value allows the cipher to expand cipher
973  /// text during encryption or shrink plain text during decryption.
974  /// \details This member function is used by CBC-CTS and OCB modes.
975  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
976  virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
977 
978  /// \brief Provides the size of the last block
979  /// \returns the minimum size of the last block
980  /// \details MinLastBlockSize() returns the minimum size of the last block. 0 indicates the last
981  /// block is not special.
982  /// \details MandatoryBlockSize() enlists one of two behaviors. First, if MandatoryBlockSize()
983  /// returns 1, then the cipher can be streamed and ProcessData() is called with the tail bytes.
984  /// Second, if MandatoryBlockSize() returns non-0, then the string of bytes is padded to
985  /// MandatoryBlockSize() according to the padding mode. Then, ProcessData() is called with the
986  /// padded string of bytes.
987  /// \details Some authenticated encryption modes are not expressed well with MandatoryBlockSize()
988  /// and MinLastBlockSize(). For example, AES/OCB uses 16-byte blocks (MandatoryBlockSize = 16)
989  /// and the last block requires special processing (MinLastBlockSize = 0). However, 0 is a valid
990  /// last block size for OCB and the special processing is custom padding, and not standard PKCS
991  /// padding. In response an unambiguous IsLastBlockSpecial() was added.
992  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
993  virtual unsigned int MinLastBlockSize() const {return 0;}
994 
995  /// \brief Determines if the last block receives special processing
996  /// \returns true if the last block reveives special processing, false otherwise.
997  /// \details Some authenticated encryption modes are not expressed well with
998  /// MandatoryBlockSize() and MinLastBlockSize(). For example, AES/OCB uses
999  /// 16-byte blocks (MandatoryBlockSize = 16) and the last block requires special processing
1000  /// (MinLastBlockSize = 0). However, 0 is a valid last block size for OCB and the special
1001  /// processing is custom padding, and not standard PKCS padding. In response an
1002  /// unambiguous IsLastBlockSpecial() was added.
1003  /// \details When IsLastBlockSpecial() returns false nothing special happens. All the former
1004  /// rules and behaviors apply. This is the default behavior of IsLastBlockSpecial().
1005  /// \details When IsLastBlockSpecial() returns true four things happen. First, MinLastBlockSize = 0
1006  /// means 0 is a valid block size that should be processed. Second, standard block cipher padding is
1007  /// \a not \a applied. Third, the caller supplies an outString is larger than inString by
1008  /// <tt>2*MandatoryBlockSize()</tt>. That is, there's a reserve available when processing the last block.
1009  /// Fourth, the cipher is responsible for finalization like custom padding. The cipher will tell
1010  /// the library how many bytes were processed or used by returning the appropriate value from
1011  /// ProcessLastBlock().
1012  /// \details The return value of ProcessLastBlock() indicates how many bytes were written to
1013  /// <tt>outString</tt>. A filter pipelining data will send <tt>outString</tt> and up to <tt>outLength</tt>
1014  /// to an <tt>AttachedTransformation()</tt> for additional processing. Below is an example of the code
1015  /// used in <tt>StreamTransformationFilter::LastPut</tt>.
1016  /// <pre> if (m_cipher.IsLastBlockSpecial())
1017  /// {
1018  /// size_t reserve = 2*m_cipher.MandatoryBlockSize();
1019  /// space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, length+reserve);
1020  /// length = m_cipher.ProcessLastBlock(space, length+reserve, inString, length);
1021  /// AttachedTransformation()->Put(space, length);
1022  /// return;
1023  /// }</pre>
1024  /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
1025  /// \since Crypto++ 6.0
1026  virtual bool IsLastBlockSpecial() const {return false;}
1027 
1028  /// \brief Encrypt or decrypt a string of bytes
1029  /// \param inoutString the string to process
1030  /// \param length the size of the inoutString, in bytes
1031  /// \details Internally, the base class implementation calls ProcessData().
1032  inline void ProcessString(byte *inoutString, size_t length)
1033  {ProcessData(inoutString, inoutString, length);}
1034 
1035  /// \brief Encrypt or decrypt a string of bytes
1036  /// \param outString the output string to process
1037  /// \param inString the input string to process
1038  /// \param length the size of the input and output strings, in bytes
1039  /// \details Internally, the base class implementation calls ProcessData().
1040  inline void ProcessString(byte *outString, const byte *inString, size_t length)
1041  {ProcessData(outString, inString, length);}
1042 
1043  /// \brief Encrypt or decrypt a byte
1044  /// \param input the input byte to process
1045  /// \details Internally, the base class implementation calls ProcessData() with a size of 1.
1046  inline byte ProcessByte(byte input)
1047  {ProcessData(&input, &input, 1); return input;}
1048 
1049  /// \brief Determines whether the cipher supports random access
1050  /// \returns true if the cipher supports random access, false otherwise
1051  virtual bool IsRandomAccess() const =0;
1052 
1053  /// \brief Seek to an absolute position
1054  /// \param pos position to seek
1055  /// \throws NotImplemented
1056  /// \details The base class implementation throws NotImplemented. The function
1057  /// \ref CRYPTOPP_ASSERT "asserts" IsRandomAccess() in debug builds.
1058  virtual void Seek(lword pos)
1059  {
1060  CRYPTOPP_UNUSED(pos);
1061  CRYPTOPP_ASSERT(!IsRandomAccess());
1062  throw NotImplemented("StreamTransformation: this object doesn't support random access");
1063  }
1064 
1065  /// \brief Determines whether the cipher is self-inverting
1066  /// \returns true if the cipher is self-inverting, false otherwise
1067  /// \details IsSelfInverting determines whether this transformation is
1068  /// self-inverting (e.g. xor with a keystream).
1069  virtual bool IsSelfInverting() const =0;
1070 
1071  /// \brief Determines if the cipher is being operated in its forward direction
1072  /// \returns true if DIR is ENCRYPTION, false otherwise
1073  /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
1074  virtual bool IsForwardTransformation() const =0;
1075 };
1076 
1077 /// \brief Interface for hash functions and data processing part of MACs
1078 /// \details HashTransformation objects are stateful. They are created in an initial state,
1079 /// change state as Update() is called, and return to the initial
1080 /// state when Final() is called. This interface allows a large message to
1081 /// be hashed in pieces by calling Update() on each piece followed by
1082 /// calling Final().
1083 /// \sa HashFilter(), HashVerificationFilter()
1084 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
1085 {
1086 public:
1087  virtual ~HashTransformation() {}
1088 
1089  /// \brief Provides a reference to this object
1090  /// \return A reference to this object
1091  /// \details Useful for passing a temporary object to a function that takes a non-const reference
1092  HashTransformation& Ref() {return *this;}
1093 
1094  /// \brief Updates a hash with additional input
1095  /// \param input the additional input as a buffer
1096  /// \param length the size of the buffer, in bytes
1097  virtual void Update(const byte *input, size_t length) =0;
1098 
1099  /// \brief Request space which can be written into by the caller
1100  /// \param size the requested size of the buffer
1101  /// \details The purpose of this method is to help avoid extra memory allocations.
1102  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1103  /// size is the requested size of the buffer. When the call returns, size is the size of
1104  /// the array returned to the caller.
1105  /// \details The base class implementation sets size to 0 and returns NULL or nullptr.
1106  /// \note Some objects, like ArraySink, cannot create a space because its fixed.
1107  virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULLPTR;}
1108 
1109  /// \brief Computes the hash of the current message
1110  /// \param digest a pointer to the buffer to receive the hash
1111  /// \details Final() restarts the hash for a new message.
1112  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1113  /// the output byte buffer is large enough for the digest.
1114  virtual void Final(byte *digest)
1115  {TruncatedFinal(digest, DigestSize());}
1116 
1117  /// \brief Restart the hash
1118  /// \details Discards the current state, and restart for a new message
1119  virtual void Restart()
1120  {TruncatedFinal(NULLPTR, 0);}
1121 
1122  /// Provides the digest size of the hash
1123  /// \return the digest size of the hash.
1124  virtual unsigned int DigestSize() const =0;
1125 
1126  /// Provides the tag size of the hash
1127  /// \return the tag size of the hash.
1128  /// \details Same as DigestSize().
1129  unsigned int TagSize() const {return DigestSize();}
1130 
1131  /// \brief Provides the block size of the compression function
1132  /// \return the block size of the compression function, in bytes
1133  /// \details BlockSize() will return 0 if the hash is not block based. For example,
1134  /// SHA3 is a recursive hash (not an iterative hash), and it does not have a block size.
1135  virtual unsigned int BlockSize() const {return 0;}
1136 
1137  /// \brief Provides the input block size most efficient for this hash.
1138  /// \return The input block size that is most efficient for the cipher
1139  /// \details The base class implementation returns MandatoryBlockSize().
1140  /// \details Optimal input length is
1141  /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>.
1142  virtual unsigned int OptimalBlockSize() const {return 1;}
1143 
1144  /// \brief Provides input and output data alignment for optimal performance
1145  /// \return the input data alignment that provides optimal performance
1146  /// \sa GetAlignment() and OptimalBlockSize()
1147  virtual unsigned int OptimalDataAlignment() const;
1148 
1149  /// \brief Updates the hash with additional input and computes the hash of the current message
1150  /// \param digest a pointer to the buffer to receive the hash
1151  /// \param input the additional input as a buffer
1152  /// \param length the size of the buffer, in bytes
1153  /// \details Use this if your input is in one piece and you don't want to call Update()
1154  /// and Final() separately
1155  /// \details CalculateDigest() restarts the hash for the next message.
1156  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1157  /// the output byte buffer is large enough for the digest.
1158  virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
1159  {Update(input, length); Final(digest);}
1160 
1161  /// \brief Verifies the hash of the current message
1162  /// \param digest a pointer to the buffer of an \a existing hash
1163  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1164  /// \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
1165  /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
1166  /// a constant time comparison function. digestLength cannot exceed DigestSize().
1167  /// \details Verify() restarts the hash for the next message.
1168  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1169  /// the output byte buffer is large enough for the digest.
1170  virtual bool Verify(const byte *digest)
1171  {return TruncatedVerify(digest, DigestSize());}
1172 
1173  /// \brief Updates the hash with additional input and verifies the hash of the current message
1174  /// \param digest a pointer to the buffer of an \a existing hash
1175  /// \param input the additional input as a buffer
1176  /// \param length the size of the buffer, in bytes
1177  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1178  /// \throws ThrowIfInvalidTruncatedSize() if the existing hash's size exceeds DigestSize()
1179  /// \details Use this if your input is in one piece and you don't want to call Update()
1180  /// and Verify() separately
1181  /// \details VerifyDigest() performs a bitwise compare on the buffers using VerifyBufsEqual(),
1182  /// which is a constant time comparison function. digestLength cannot exceed DigestSize().
1183  /// \details VerifyDigest() restarts the hash for the next message.
1184  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1185  /// the output byte buffer is large enough for the digest.
1186  virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
1187  {Update(input, length); return Verify(digest);}
1188 
1189  /// \brief Computes the hash of the current message
1190  /// \param digest a pointer to the buffer to receive the hash
1191  /// \param digestSize the size of the truncated digest, in bytes
1192  /// \details TruncatedFinal() call Final() and then copies digestSize bytes to digest.
1193  /// The hash is restarted the hash for the next message.
1194  virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
1195 
1196  /// \brief Updates the hash with additional input and computes the hash of the current message
1197  /// \param digest a pointer to the buffer to receive the hash
1198  /// \param digestSize the length of the truncated hash, in bytes
1199  /// \param input the additional input as a buffer
1200  /// \param length the size of the buffer, in bytes
1201  /// \details Use this if your input is in one piece and you don't want to call Update()
1202  /// and CalculateDigest() separately.
1203  /// \details CalculateTruncatedDigest() restarts the hash for the next message.
1204  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1205  /// the output byte buffer is large enough for the digest.
1206  virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
1207  {Update(input, length); TruncatedFinal(digest, digestSize);}
1208 
1209  /// \brief Verifies the hash of the current message
1210  /// \param digest a pointer to the buffer of an \a existing hash
1211  /// \param digestLength the size of the truncated hash, in bytes
1212  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1213  /// \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
1214  /// \details TruncatedVerify() is a truncated version of Verify(). It can operate on a
1215  /// buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
1216  /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
1217  /// a constant time comparison function. digestLength cannot exceed DigestSize().
1218  /// \details TruncatedVerify() restarts the hash for the next message.
1219  virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
1220 
1221  /// \brief Updates the hash with additional input and verifies the hash of the current message
1222  /// \param digest a pointer to the buffer of an \a existing hash
1223  /// \param digestLength the size of the truncated hash, in bytes
1224  /// \param input the additional input as a buffer
1225  /// \param length the size of the buffer, in bytes
1226  /// \return \p true if the existing hash matches the computed hash, \p false otherwise
1227  /// \throws ThrowIfInvalidTruncatedSize() if digestLength exceeds DigestSize()
1228  /// \details Use this if your input is in one piece and you don't want to call Update()
1229  /// and TruncatedVerify() separately.
1230  /// \details VerifyTruncatedDigest() is a truncated version of VerifyDigest(). It can operate
1231  /// on a buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
1232  /// \details VerifyTruncatedDigest() restarts the hash for the next message.
1233  /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
1234  /// the output byte buffer is large enough for the digest.
1235  virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
1236  {Update(input, length); return TruncatedVerify(digest, digestLength);}
1237 
1238 protected:
1239  /// \brief Validates a truncated digest size
1240  /// \param size the requested digest size
1241  /// \throws InvalidArgument if the algorithm's digest size cannot be truncated to the requested size
1242  /// \details Throws an exception when the truncated digest size is greater than DigestSize()
1243  void ThrowIfInvalidTruncatedSize(size_t size) const;
1244 };
1245 
1246 /// \brief Interface for one direction (encryption or decryption) of a block cipher
1247 /// \details These objects usually should not be used directly. See BlockTransformation for more details.
1248 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
1249 {
1250 protected:
1251  const Algorithm & GetAlgorithm() const {return *this;}
1252 };
1253 
1254 /// \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode
1255 /// \details These objects usually should not be used directly. See StreamTransformation for more details.
1256 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
1257 {
1258 protected:
1259  const Algorithm & GetAlgorithm() const {return *this;}
1260 };
1261 
1262 /// \brief Interface for message authentication codes
1263 /// \details These objects usually should not be used directly. See HashTransformation for more details.
1264 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
1265 {
1266 protected:
1267  const Algorithm & GetAlgorithm() const {return *this;}
1268 };
1269 
1270 /// \brief Interface for authenticated encryption modes of operation
1271 /// \details AuthenticatedSymmetricCipher() provides the interface for one direction
1272 /// (encryption or decryption) of a stream cipher or block cipher mode with authentication. The
1273 /// StreamTransformation() part of this interface is used to encrypt or decrypt the data. The
1274 /// MessageAuthenticationCode() part of the interface is used to input additional authenticated
1275 /// data (AAD), which is MAC'ed but not encrypted. The MessageAuthenticationCode() part is also
1276 /// used to generate and verify the MAC.
1277 /// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
1278 /// and OCB mode. All modes implement AuthenticatedSymmetricCipher() and the motivation for
1279 /// the API, like calling AAD a &quot;header&quot;, can be found in Bellare, Rogaway and
1280 /// Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX Mode of
1281 /// Operation</A>. The EAX paper suggested a basic API to help standardize AEAD schemes in
1282 /// software and promote adoption of the modes.
1283 /// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
1284 /// Encryption</A> on the Crypto++ wiki.
1285 /// \since Crypto++ 5.6.0
1286 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
1287 {
1288 public:
1289  virtual ~AuthenticatedSymmetricCipher() {}
1290 
1291  /// \brief Exception thrown when the object is in the wrong state for the operation
1292  /// \details this indicates that a member function was called in the wrong state, for example trying to encrypt
1293  /// a message before having set the key or IV
1294  class BadState : public Exception
1295  {
1296  public:
1297  explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
1298  explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
1299  };
1300 
1301  /// \brief Provides the maximum length of AAD that can be input
1302  /// \return the maximum length of AAD that can be input before the encrypted data
1303  virtual lword MaxHeaderLength() const =0;
1304  /// \brief Provides the maximum length of encrypted data
1305  /// \return the maximum length of encrypted data
1306  virtual lword MaxMessageLength() const =0;
1307  /// \brief Provides the the maximum length of AAD
1308  /// \return the maximum length of AAD that can be input after the encrypted data
1309  virtual lword MaxFooterLength() const {return 0;}
1310  /// \brief Determines if data lengths must be specified prior to inputting data
1311  /// \return true if the data lengths are required before inputting data, false otherwise
1312  /// \details if this function returns true, SpecifyDataLengths() must be called before attempting to input data.
1313  /// This is the case for some schemes, such as CCM.
1314  /// \sa SpecifyDataLengths()
1315  virtual bool NeedsPrespecifiedDataLengths() const {return false;}
1316  /// \brief Prespecifies the data lengths
1317  /// \details this function only needs to be called if NeedsPrespecifiedDataLengths() returns true
1318  /// \sa NeedsPrespecifiedDataLengths()
1319  void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
1320  /// \brief Encrypts and calculates a MAC in one call
1321  /// \details EncryptAndAuthenticate() encrypts and generates the MAC in one call. The function will truncate MAC if
1322  /// <tt>macSize < TagSize()</tt>.
1323  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);
1324  /// \brief Decrypts and verifies a MAC in one call
1325  /// \return true if the MAC is valid and the decoding succeeded, false otherwise
1326  /// \details DecryptAndVerify() decrypts and verifies the MAC in one call. The function returns true iff MAC is valid.
1327  /// DecryptAndVerify() will assume MAC is truncated if <tt>macLength < TagSize()</tt>.
1328  virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macLength, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength);
1329 
1330  /// \brief Provides the name of this algorithm
1331  /// \return the standard algorithm name
1332  /// \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms
1333  /// do not have standard names yet. For example, there is no standard algorithm name for
1334  /// Shoup's ECIES.
1335  virtual std::string AlgorithmName() const;
1336 
1337 protected:
1338  const Algorithm & GetAlgorithm() const
1339  {return *static_cast<const MessageAuthenticationCode *>(this);}
1340  virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
1341  {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);}
1342 };
1343 
1344 /// \brief Interface for random number generators
1345 /// \details The library provides a number of random number generators, from software based
1346 /// to hardware based generators.
1347 /// \details All generated values are uniformly distributed over the range specified.
1348 /// \since Crypto++ 3.1
1349 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
1350 {
1351 public:
1352  virtual ~RandomNumberGenerator() {}
1353 
1354  /// \brief Update RNG state with additional unpredictable values
1355  /// \param input the entropy to add to the generator
1356  /// \param length the size of the input buffer
1357  /// \throws NotImplemented
1358  /// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy()
1359  /// to test for the ability to use additional entropy.
1360  /// \details If a derived class does not override IncorporateEntropy(), then the base class
1361  /// throws NotImplemented.
1362  virtual void IncorporateEntropy(const byte *input, size_t length)
1363  {
1364  CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
1365  throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
1366  }
1367 
1368  /// \brief Determines if a generator can accept additional entropy
1369  /// \return true if IncorporateEntropy() is implemented
1370  virtual bool CanIncorporateEntropy() const {return false;}
1371 
1372  /// \brief Generate new random byte and return it
1373  /// \return a random 8-bit byte
1374  /// \details Default implementation calls GenerateBlock() with one byte.
1375  /// \details All generated values are uniformly distributed over the range specified within the
1376  /// the constraints of a particular generator.
1377  virtual byte GenerateByte();
1378 
1379  /// \brief Generate new random bit and return it
1380  /// \return a random bit
1381  /// \details The default implementation calls GenerateByte() and return its lowest bit.
1382  /// \details All generated values are uniformly distributed over the range specified within the
1383  /// the constraints of a particular generator.
1384  virtual unsigned int GenerateBit();
1385 
1386  /// \brief Generate a random 32 bit word in the range min to max, inclusive
1387  /// \param min the lower bound of the range
1388  /// \param max the upper bound of the range
1389  /// \return a random 32-bit word
1390  /// \details The default implementation calls Crop() on the difference between max and
1391  /// min, and then returns the result added to min.
1392  /// \details All generated values are uniformly distributed over the range specified within the
1393  /// the constraints of a particular generator.
1394  virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL);
1395 
1396  /// \brief Generate random array of bytes
1397  /// \param output the byte buffer
1398  /// \param size the length of the buffer, in bytes
1399  /// \details All generated values are uniformly distributed over the range specified within the
1400  /// the constraints of a particular generator.
1401  /// \note A derived generator \a must override either GenerateBlock() or
1402  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1403  virtual void GenerateBlock(byte *output, size_t size);
1404 
1405  /// \brief Generate random bytes into a BufferedTransformation
1406  /// \param target the BufferedTransformation object which receives the bytes
1407  /// \param channel the channel on which the bytes should be pumped
1408  /// \param length the number of bytes to generate
1409  /// \details The default implementation calls GenerateBlock() and pumps the result into
1410  /// the DEFAULT_CHANNEL of the target.
1411  /// \details All generated values are uniformly distributed over the range specified within the
1412  /// the constraints of a particular generator.
1413  /// \note A derived generator \a must override either GenerateBlock() or
1414  /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
1415  virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
1416 
1417  /// \brief Generate and discard n bytes
1418  /// \param n the number of bytes to generate and discard
1419  virtual void DiscardBytes(size_t n);
1420 
1421  /// \brief Randomly shuffle the specified array
1422  /// \param begin an iterator to the first element in the array
1423  /// \param end an iterator beyond the last element in the array
1424  /// \details The resulting permutation is uniformly distributed.
1425  template <class IT> void Shuffle(IT begin, IT end)
1426  {
1427  // TODO: What happens if there are more than 2^32 elements?
1428  for (; begin != end; ++begin)
1429  std::iter_swap(begin, begin + GenerateWord32(0, static_cast<word32>(end-begin-1)));
1430  }
1431 };
1432 
1433 /// \brief Interface for key derivation functions
1434 /// \since Crypto++ 7.0
1435 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm
1436 {
1437 public:
1438  virtual ~KeyDerivationFunction() {}
1439 
1440  /// \brief Provides the name of this algorithm
1441  /// \return the standard algorithm name
1442  virtual std::string AlgorithmName() const =0;
1443 
1444  /// \brief Determine minimum number of bytes
1445  /// \returns Minimum number of bytes which can be derived
1446  virtual size_t MinDerivedLength() const;
1447 
1448  /// \brief Determine maximum number of bytes
1449  /// \returns Maximum number of bytes which can be derived
1450  virtual size_t MaxDerivedLength() const;
1451 
1452  /// \brief Returns a valid key length for the derivation function
1453  /// \param keylength the size of the derived key, in bytes
1454  /// \returns the valid key length, in bytes
1455  virtual size_t GetValidDerivedLength(size_t keylength) const =0;
1456 
1457  /// \brief Returns whether keylength is a valid key length
1458  /// \param keylength the requested keylength
1459  /// \return true if the derived keylength is valid, false otherwise
1460  /// \details Internally the function calls GetValidKeyLength()
1461  virtual bool IsValidDerivedLength(size_t keylength) const {
1462  return keylength == GetValidDerivedLength(keylength);
1463  }
1464 
1465  /// \brief Derive a key from a seed
1466  /// \param derived the derived output buffer
1467  /// \param derivedLen the size of the derived buffer, in bytes
1468  /// \param secret the seed input buffer
1469  /// \param secretLen the size of the secret buffer, in bytes
1470  /// \param params additional initialization parameters to configure this object
1471  /// \returns the number of iterations performed
1472  /// \throws InvalidDerivedLength if <tt>derivedLen</tt> is invalid for the scheme
1473  /// \details DeriveKey() provides a standard interface to derive a key from
1474  /// a secret seed and other parameters. Each class that derives from KeyDerivationFunction
1475  /// provides an overload that accepts most parameters used by the derivation function.
1476  /// \details the number of iterations performed by DeriveKey() may be 1. For example, a
1477  /// scheme like HKDF does not use the iteration count so it returns 1.
1478  virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params = g_nullNameValuePairs) const =0;
1479 
1480  /// \brief Set or change parameters
1481  /// \param params additional initialization parameters to configure this object
1482  /// \details SetParameters() is useful for setting common parameters when an object is
1483  /// reused. Some derivation function classes may choose to implement it.
1484  virtual void SetParameters(const NameValuePairs& params);
1485 
1486 protected:
1487  /// \brief Returns the base class Algorithm
1488  /// \return the base class Algorithm
1489  virtual const Algorithm & GetAlgorithm() const =0;
1490 
1491  /// \brief Validates the derived key length
1492  /// \param length the size of the derived key material, in bytes
1493  /// \throws InvalidKeyLength if the key length is invalid
1494  void ThrowIfInvalidDerivedLength(size_t length) const;
1495 };
1496 
1497 /// \brief Interface for password based key derivation functions
1498 /// \since Crypto++ 7.0
1500 {
1501 };
1502 
1503 /// \brief Random Number Generator that does not produce random numbers
1504 /// \return reference that can be passed to functions that require a RandomNumberGenerator
1505 /// \details NullRNG() returns a reference that can be passed to functions that require a
1506 /// RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented
1507 /// when a generation function is called.
1508 /// \sa ClassNullRNG, PK_SignatureScheme::IsProbabilistic()
1509 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
1510 
1511 class WaitObjectContainer;
1512 class CallStack;
1513 
1514 /// \brief Interface for objects that can be waited on.
1515 class CRYPTOPP_NO_VTABLE Waitable
1516 {
1517 public:
1518  virtual ~Waitable() {}
1519 
1520  /// \brief Maximum number of wait objects that this object can return
1521  /// \return the maximum number of wait objects
1522  virtual unsigned int GetMaxWaitObjectCount() const =0;
1523 
1524  /// \brief Retrieves waitable objects
1525  /// \param container the wait container to receive the references to the objects.
1526  /// \param callStack CallStack() object used to select waitable objects
1527  /// \details GetWaitObjects() is usually called in one of two ways. First, it can
1528  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1529  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1530  /// parameter, it can be called like
1531  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1532  virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
1533 
1534  /// \brief Wait on this object
1535  /// \return true if the wait succeeded, false otherwise
1536  /// \details Wait() is the same as creating an empty container, calling GetWaitObjects(), and then calling
1537  /// Wait() on the container.
1538  bool Wait(unsigned long milliseconds, CallStack const& callStack);
1539 };
1540 
1541 /// \brief Interface for buffered transformations
1542 /// \details BufferedTransformation is a generalization of BlockTransformation,
1543 /// StreamTransformation and HashTransformation.
1544 /// \details A buffered transformation is an object that takes a stream of bytes as input (this may
1545 /// be done in stages), does some computation on them, and then places the result into an internal
1546 /// buffer for later retrieval. Any partial result already in the output buffer is not modified
1547 /// by further input.
1548 /// \details If a method takes a "blocking" parameter, and you pass false for it, then the method
1549 /// will return before all input has been processed if the input cannot be processed without waiting
1550 /// (for network buffers to become available, for example). In this case the method will return true
1551 /// or a non-zero integer value. When this happens you must continue to call the method with the same
1552 /// parameters until it returns false or zero, before calling any other method on it or attached
1553 /// /p BufferedTransformation. The integer return value in this case is approximately
1554 /// the number of bytes left to be processed, and can be used to implement a progress bar.
1555 /// \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on
1556 /// the signal to attached BufferedTransformation objects, with propagation decremented at each
1557 /// step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation.
1558 /// \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual
1559 /// number of bytes retrieved, which is the lesser of the request number and MaxRetrievable().
1560 /// \details \a Most of the input functions, like Put() and PutWord32(), return the number of
1561 /// bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value
1562 /// means bytes remain to be processed.
1563 /// \nosubgrouping
1564 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
1565 {
1566 public:
1567  virtual ~BufferedTransformation() {}
1568 
1569  /// \brief Construct a BufferedTransformation
1571 
1572  /// \brief Provides a reference to this object
1573  /// \return A reference to this object
1574  /// \details Useful for passing a temporary object to a function that takes a non-const reference
1575  BufferedTransformation& Ref() {return *this;}
1576 
1577  /// \name INPUT
1578  //@{
1579 
1580  /// \brief Input a byte for processing
1581  /// \param inByte the 8-bit byte (octet) to be processed.
1582  /// \param blocking specifies whether the object should block when processing input.
1583  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1584  /// bytes were processed.
1585  /// \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>.
1586  size_t Put(byte inByte, bool blocking=true)
1587  {return Put(&inByte, 1, blocking);}
1588 
1589  /// \brief Input a byte buffer for processing
1590  /// \param inString the byte buffer to process
1591  /// \param length the size of the string, in bytes
1592  /// \param blocking specifies whether the object should block when processing input
1593  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1594  /// bytes were processed.
1595  /// \details Internally, Put() calls Put2().
1596  size_t Put(const byte *inString, size_t length, bool blocking=true)
1597  {return Put2(inString, length, 0, blocking);}
1598 
1599  /// Input a 16-bit word for processing.
1600  /// \param value the 16-bit value to be processed
1601  /// \param order the ByteOrder of the value to be processed.
1602  /// \param blocking specifies whether the object should block when processing input
1603  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1604  /// bytes were processed.
1605  size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1606 
1607  /// Input a 32-bit word for processing.
1608  /// \param value the 32-bit value to be processed.
1609  /// \param order the ByteOrder of the value to be processed.
1610  /// \param blocking specifies whether the object should block when processing input.
1611  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1612  /// bytes were processed.
1613  size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1614 
1615  /// \brief Request space which can be written into by the caller
1616  /// \param size the requested size of the buffer
1617  /// \return byte pointer to the space to input data
1618  /// \details The purpose of this method is to help avoid extra memory allocations.
1619  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1620  /// size is the requested size of the buffer. When the call returns, size is the size of
1621  /// the array returned to the caller.
1622  /// \details The base class implementation sets size to 0 and returns NULL.
1623  /// \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
1624  /// an ArraySink, the pointer to the array is returned and the size is remaining size.
1625  virtual byte * CreatePutSpace(size_t &size)
1626  {size=0; return NULLPTR;}
1627 
1628  /// \brief Determines whether input can be modified by the callee
1629  /// \return true if input can be modified, false otherwise
1630  /// \details The base class implementation returns false.
1631  virtual bool CanModifyInput() const
1632  {return false;}
1633 
1634  /// \brief Input multiple bytes that may be modified by callee.
1635  /// \param inString the byte buffer to process
1636  /// \param length the size of the string, in bytes
1637  /// \param blocking specifies whether the object should block when processing input
1638  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1639  /// bytes were processed.
1640  size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
1641  {return PutModifiable2(inString, length, 0, blocking);}
1642 
1643  /// \brief Signals the end of messages to the object
1644  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1645  /// \param blocking specifies whether the object should block when processing input
1646  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1647  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1648  bool MessageEnd(int propagation=-1, bool blocking=true)
1649  {return !!Put2(NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
1650 
1651  /// \brief Input multiple bytes for processing and signal the end of a message
1652  /// \param inString the byte buffer to process
1653  /// \param length the size of the string, in bytes
1654  /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
1655  /// \param blocking specifies whether the object should block when processing input
1656  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1657  /// bytes were processed.
1658  /// \details Internally, PutMessageEnd() calls Put2() with a modified propagation to
1659  /// ensure all attached transformations finish processing the message.
1660  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1661  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1662  size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
1663  {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
1664 
1665  /// \brief Input multiple bytes for processing
1666  /// \param inString the byte buffer to process
1667  /// \param length the size of the string, in bytes
1668  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
1669  /// \param blocking specifies whether the object should block when processing input
1670  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1671  /// bytes were processed.
1672  /// \details Derived classes must implement Put2().
1673  virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
1674 
1675  /// \brief Input multiple bytes that may be modified by callee.
1676  /// \param inString the byte buffer to process.
1677  /// \param length the size of the string, in bytes.
1678  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
1679  /// \param blocking specifies whether the object should block when processing input.
1680  /// \return the number of bytes that remain in the block (i.e., bytes not processed). 0 indicates all
1681  /// bytes were processed.
1682  /// \details Internally, PutModifiable2() calls Put2().
1683  virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
1684  {return Put2(inString, length, messageEnd, blocking);}
1685 
1686  /// \brief Exception thrown by objects that have \a not implemented nonblocking input processing
1687  /// \details BlockingInputOnly inherits from NotImplemented
1689  {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
1690  //@}
1691 
1692  /// \name WAITING
1693  //@{
1694  /// \brief Retrieves the maximum number of waitable objects
1695  unsigned int GetMaxWaitObjectCount() const;
1696 
1697  /// \brief Retrieves waitable objects
1698  /// \param container the wait container to receive the references to the objects
1699  /// \param callStack CallStack() object used to select waitable objects
1700  /// \details GetWaitObjects is usually called in one of two ways. First, it can
1701  /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1702  /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
1703  /// parameter, it can be called like
1704  /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1705  void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
1706  //@} // WAITING
1707 
1708  /// \name SIGNALS
1709  //@{
1710 
1711  /// \brief Initialize or reinitialize this object, without signal propagation
1712  /// \param parameters a set of NameValuePairs to initialize this object
1713  /// \throws NotImplemented
1714  /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
1715  /// number of arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1716  /// all possible combintations of configurable parameters.
1717  /// \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization
1718  /// should be propagated, then use the Initialize() function.
1719  /// \details If a derived class does not override IsolatedInitialize(), then the base class throws
1720  /// NotImplemented.
1721  virtual void IsolatedInitialize(const NameValuePairs &parameters) {
1722  CRYPTOPP_UNUSED(parameters);
1723  throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
1724  }
1725 
1726  /// \brief Flushes data buffered by this object, without signal propagation
1727  /// \param hardFlush indicates whether all data should be flushed
1728  /// \param blocking specifies whether the object should block when processing input
1729  /// \note hardFlush must be used with care
1730  virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
1731 
1732  /// \brief Marks the end of a series of messages, without signal propagation
1733  /// \param blocking specifies whether the object should block when completing the processing on
1734  /// the current series of messages
1735  virtual bool IsolatedMessageSeriesEnd(bool blocking)
1736  {CRYPTOPP_UNUSED(blocking); return false;}
1737 
1738  /// \brief Initialize or reinitialize this object, with signal propagation
1739  /// \param parameters a set of NameValuePairs to initialize or reinitialize this object
1740  /// \param propagation the number of attached transformations the Initialize() signal should be passed
1741  /// \details Initialize() is used to initialize or reinitialize an object using a variable number of
1742  /// arbitrarily typed arguments. The function avoids the need for multiple constructors providing
1743  /// all possible combintations of configurable parameters.
1744  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1745  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1746  virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
1747 
1748  /// \brief Flush buffered input and/or output, with signal propagation
1749  /// \param hardFlush is used to indicate whether all data should be flushed
1750  /// \param propagation the number of attached transformations the Flush() signal should be passed
1751  /// \param blocking specifies whether the object should block when processing input
1752  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1753  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1754  /// \note Hard flushes must be used with care. It means try to process and output everything, even if
1755  /// there may not be enough data to complete the action. For example, hard flushing a HexDecoder
1756  /// would cause an error if you do it after inputing an odd number of hex encoded characters.
1757  /// \note For some types of filters, like ZlibDecompressor, hard flushes can only
1758  /// be done at "synchronization points". These synchronization points are positions in the data
1759  /// stream that are created by hard flushes on the corresponding reverse filters, in this
1760  /// example ZlibCompressor. This is useful when zlib compressed data is moved across a
1761  /// network in packets and compression state is preserved across packets, as in the SSH2 protocol.
1762  virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
1763 
1764  /// \brief Marks the end of a series of messages, with signal propagation
1765  /// \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
1766  /// \param blocking specifies whether the object should block when processing input
1767  /// \details Each object that receives the signal will perform its processing, decrement
1768  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
1769  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1770  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1771  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
1772  virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
1773 
1774  /// \brief Set propagation of automatically generated and transferred signals
1775  /// \param propagation then new value
1776  /// \details Setting propagation to <tt>0</tt> means do not automatically generate signals. Setting
1777  /// propagation to <tt>-1</tt> means unlimited propagation.
1778  virtual void SetAutoSignalPropagation(int propagation)
1779  {CRYPTOPP_UNUSED(propagation);}
1780 
1781  /// \brief Retrieve automatic signal propagation value
1782  /// \return the number of attached transformations the signal is propagated to. 0 indicates
1783  /// the signal is only witnessed by this object
1784  virtual int GetAutoSignalPropagation() const {return 0;}
1785 public:
1786 
1787  /// \name RETRIEVAL OF ONE MESSAGE
1788  //@{
1789 
1790  /// \brief Provides the number of bytes ready for retrieval
1791  /// \return the number of bytes ready for retrieval
1792  /// \details All retrieval functions return the actual number of bytes retrieved, which is
1793  /// the lesser of the request number and MaxRetrievable()
1794  virtual lword MaxRetrievable() const;
1795 
1796  /// \brief Determines whether bytes are ready for retrieval
1797  /// \returns true if bytes are available for retrieval, false otherwise
1798  virtual bool AnyRetrievable() const;
1799 
1800  /// \brief Retrieve a 8-bit byte
1801  /// \param outByte the 8-bit value to be retrieved
1802  /// \return the number of bytes consumed during the call.
1803  /// \details Use the return value of Get to detect short reads.
1804  virtual size_t Get(byte &outByte);
1805 
1806  /// \brief Retrieve a block of bytes
1807  /// \param outString a block of bytes
1808  /// \param getMax the number of bytes to Get
1809  /// \return the number of bytes consumed during the call.
1810  /// \details Use the return value of Get to detect short reads.
1811  virtual size_t Get(byte *outString, size_t getMax);
1812 
1813  /// \brief Peek a 8-bit byte
1814  /// \param outByte the 8-bit value to be retrieved
1815  /// \return the number of bytes read during the call.
1816  /// \details Peek does not remove bytes from the object. Use the return value of
1817  /// Get() to detect short reads.
1818  virtual size_t Peek(byte &outByte) const;
1819 
1820  /// \brief Peek a block of bytes
1821  /// \param outString a block of bytes
1822  /// \param peekMax the number of bytes to Peek
1823  /// \return the number of bytes read during the call.
1824  /// \details Peek does not remove bytes from the object. Use the return value of
1825  /// Get() to detect short reads.
1826  virtual size_t Peek(byte *outString, size_t peekMax) const;
1827 
1828  /// \brief Retrieve a 16-bit word
1829  /// \param value the 16-bit value to be retrieved
1830  /// \param order the ByteOrder of the value to be processed.
1831  /// \return the number of bytes consumed during the call.
1832  /// \details Use the return value of GetWord16() to detect short reads.
1833  size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1834 
1835  /// \brief Retrieve a 32-bit word
1836  /// \param value the 32-bit value to be retrieved
1837  /// \param order the ByteOrder of the value to be processed.
1838  /// \return the number of bytes consumed during the call.
1839  /// \details Use the return value of GetWord16() to detect short reads.
1840  size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1841 
1842  /// \brief Peek a 16-bit word
1843  /// \param value the 16-bit value to be retrieved
1844  /// \param order the ByteOrder of the value to be processed.
1845  /// \return the number of bytes consumed during the call.
1846  /// \details Peek does not consume bytes in the stream. Use the return value
1847  /// of GetWord16() to detect short reads.
1848  size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1849 
1850  /// \brief Peek a 32-bit word
1851  /// \param value the 32-bit value to be retrieved
1852  /// \param order the ByteOrder of the value to be processed.
1853  /// \return the number of bytes consumed during the call.
1854  /// \details Peek does not consume bytes in the stream. Use the return value
1855  /// of GetWord16() to detect short reads.
1856  size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1857 
1858  /// move transferMax bytes of the buffered output to target as input
1859 
1860  /// \brief Transfer bytes from this object to another BufferedTransformation
1861  /// \param target the destination BufferedTransformation
1862  /// \param transferMax the number of bytes to transfer
1863  /// \param channel the channel on which the transfer should occur
1864  /// \return the number of bytes transferred during the call.
1865  /// \details TransferTo removes bytes from this object and moves them to the destination.
1866  /// \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2().
1867  lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
1868  {TransferTo2(target, transferMax, channel); return transferMax;}
1869 
1870  /// \brief Discard skipMax bytes from the output buffer
1871  /// \param skipMax the number of bytes to discard
1872  /// \details Skip() discards bytes from the output buffer, which is the AttachedTransformation(), if present.
1873  /// The function always returns the parameter <tt>skipMax</tt>.
1874  /// \details If you want to skip bytes from a Source, then perform the following.
1875  /// <pre>
1876  /// StringSource ss(str, false, new Redirector(TheBitBucket()));
1877  /// ss.Pump(10); // Skip 10 bytes from Source
1878  /// ss.Detach(new FilterChain(...));
1879  /// ss.PumpAll();
1880  /// </pre>
1881  virtual lword Skip(lword skipMax=LWORD_MAX);
1882 
1883  /// copy copyMax bytes of the buffered output to target as input
1884 
1885  /// \brief Copy bytes from this object to another BufferedTransformation
1886  /// \param target the destination BufferedTransformation
1887  /// \param copyMax the number of bytes to copy
1888  /// \param channel the channel on which the transfer should occur
1889  /// \return the number of bytes copied during the call.
1890  /// \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
1891  /// \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2().
1892  lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1893  {return CopyRangeTo(target, 0, copyMax, channel);}
1894 
1895  /// \brief Copy bytes from this object using an index to another BufferedTransformation
1896  /// \param target the destination BufferedTransformation
1897  /// \param position the 0-based index of the byte stream to begin the copying
1898  /// \param copyMax the number of bytes to copy
1899  /// \param channel the channel on which the transfer should occur
1900  /// \return the number of bytes copied during the call.
1901  /// \details CopyTo copies bytes from this object to the destination. The bytes remain in this
1902  /// object. Copying begins at the index position in the current stream, and not from an absolute
1903  /// position in the stream.
1904  /// \details The function returns the new position in the stream after transferring the bytes starting at the index.
1905  lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1906  {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
1907  //@}
1908 
1909  /// \name RETRIEVAL OF MULTIPLE MESSAGES
1910  //@{
1911 
1912  /// \brief Provides the number of bytes ready for retrieval
1913  /// \return the number of bytes ready for retrieval
1914  virtual lword TotalBytesRetrievable() const;
1915 
1916  /// \brief Provides the number of meesages processed by this object
1917  /// \return the number of meesages processed by this object
1918  /// \details NumberOfMessages returns number of times MessageEnd() has been
1919  /// received minus messages retrieved or skipped
1920  virtual unsigned int NumberOfMessages() const;
1921 
1922  /// \brief Determines if any messages are available for retrieval
1923  /// \returns true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
1924  /// \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
1925  virtual bool AnyMessages() const;
1926 
1927  /// \brief Start retrieving the next message
1928  /// \return true if a message is ready for retrieval
1929  /// \details GetNextMessage() returns true if a message is ready for retrieval; false
1930  /// if no more messages exist or this message is not completely retrieved.
1931  virtual bool GetNextMessage();
1932 
1933  /// \brief Skip a number of meessages
1934  /// \return 0 if the requested number of messages was skipped, non-0 otherwise
1935  /// \details SkipMessages() skips count number of messages. If there is an AttachedTransformation()
1936  /// then SkipMessages() is called on the attached transformation. If there is no attached
1937  /// transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo().
1938  virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
1939 
1940  /// \brief Transfer messages from this object to another BufferedTransformation
1941  /// \param target the destination BufferedTransformation
1942  /// \param count the number of messages to transfer
1943  /// \param channel the channel on which the transfer should occur
1944  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
1945  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
1946  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
1947  /// bytes is returned. TransferMessagesTo() does not proceed to the next message.
1948  /// \details A return value of 0 indicates all messages were successfully transferred.
1949  unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
1950  {TransferMessagesTo2(target, count, channel); return count;}
1951 
1952  /// \brief Copy messages from this object to another BufferedTransformation
1953  /// \param target the destination BufferedTransformation
1954  /// \param count the number of messages to transfer
1955  /// \param channel the channel on which the transfer should occur
1956  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
1957  /// \details CopyMessagesTo copies messages from this object and copies them to the destination.
1958  /// If all bytes are not transferred for a message, then processing stops and the number of remaining
1959  /// bytes is returned. CopyMessagesTo() does not proceed to the next message.
1960  /// \details A return value of 0 indicates all messages were successfully copied.
1961  unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
1962 
1963  /// \brief Skip all messages in the series
1964  virtual void SkipAll();
1965 
1966  /// \brief Transfer all bytes from this object to another BufferedTransformation
1967  /// \param target the destination BufferedTransformation
1968  /// \param channel the channel on which the transfer should occur
1969  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
1970  /// Internally TransferAllTo() calls TransferAllTo2().
1971  void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
1972  {TransferAllTo2(target, channel);}
1973 
1974  /// \brief Copy messages from this object to another BufferedTransformation
1975  /// \param target the destination BufferedTransformation
1976  /// \param channel the channel on which the transfer should occur
1977  /// \details CopyAllTo copies messages from this object and copies them to the destination.
1978  void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
1979 
1980  /// \brief Retrieve the next message in a series
1981  /// \return true if a message was retreved, false otherwise
1982  /// \details Internally, the base class implementation returns false.
1983  virtual bool GetNextMessageSeries() {return false;}
1984  /// \brief Provides the number of messages in a series
1985  /// \return the number of messages in this series
1986  virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
1987  /// \brief Provides the number of messages in a series
1988  /// \return the number of messages in this series
1989  virtual unsigned int NumberOfMessageSeries() const {return 0;}
1990  //@}
1991 
1992  /// \name NON-BLOCKING TRANSFER OF OUTPUT
1993  //@{
1994 
1995  // upon return, byteCount contains number of bytes that have finished being transferred,
1996  // and returns the number of bytes left in the current transfer block
1997 
1998  /// \brief Transfer bytes from this object to another BufferedTransformation
1999  /// \param target the destination BufferedTransformation
2000  /// \param byteCount the number of bytes to transfer
2001  /// \param channel the channel on which the transfer should occur
2002  /// \param blocking specifies whether the object should block when processing input
2003  /// \return the number of bytes that remain in the transfer block (i.e., bytes not transferred)
2004  /// \details TransferTo() removes bytes from this object and moves them to the destination.
2005  /// Transfer begins at the index position in the current stream, and not from an absolute
2006  /// position in the stream.
2007  /// \details byteCount is an \a IN and \a OUT parameter. When the call is made,
2008  /// byteCount is the requested size of the transfer. When the call returns, byteCount is
2009  /// the number of bytes that were transferred.
2010  virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
2011 
2012  // upon return, begin contains the start position of data yet to be finished copying,
2013  // and returns the number of bytes left in the current transfer block
2014 
2015  /// \brief Copy bytes from this object to another BufferedTransformation
2016  /// \param target the destination BufferedTransformation
2017  /// \param begin the 0-based index of the first byte to copy in the stream
2018  /// \param end the 0-based index of the last byte to copy in the stream
2019  /// \param channel the channel on which the transfer should occur
2020  /// \param blocking specifies whether the object should block when processing input
2021  /// \return the number of bytes that remain in the copy block (i.e., bytes not copied)
2022  /// \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not
2023  /// removed from this object. Copying begins at the index position in the current stream, and
2024  /// not from an absolute position in the stream.
2025  /// \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the
2026  /// starting position of the copy. When the call returns, begin is the position of the first
2027  /// byte that was \a not copied (which may be different than end). begin can be used for
2028  /// subsequent calls to CopyRangeTo2().
2029  virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
2030 
2031  // upon return, messageCount contains number of messages that have finished being transferred,
2032  // and returns the number of bytes left in the current transfer block
2033 
2034  /// \brief Transfer messages from this object to another BufferedTransformation
2035  /// \param target the destination BufferedTransformation
2036  /// \param messageCount the number of messages to transfer
2037  /// \param channel the channel on which the transfer should occur
2038  /// \param blocking specifies whether the object should block when processing input
2039  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2040  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2041  /// \details messageCount is an \a IN and \a OUT parameter. When the call is made, messageCount is the
2042  /// the number of messages requested to be transferred. When the call returns, messageCount is the
2043  /// number of messages actually transferred.
2044  size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2045 
2046  // returns the number of bytes left in the current transfer block
2047 
2048  /// \brief Transfer all bytes from this object to another BufferedTransformation
2049  /// \param target the destination BufferedTransformation
2050  /// \param channel the channel on which the transfer should occur
2051  /// \param blocking specifies whether the object should block when processing input
2052  /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
2053  /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
2054  size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2055  //@}
2056 
2057  /// \name CHANNELS
2058  //@{
2059  /// \brief Exception thrown when a filter does not support named channels
2061  {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
2062  /// \brief Exception thrown when a filter does not recognize a named channel
2064  {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
2065 
2066  /// \brief Input a byte for processing on a channel
2067  /// \param channel the channel to process the data.
2068  /// \param inByte the 8-bit byte (octet) to be processed.
2069  /// \param blocking specifies whether the object should block when processing input.
2070  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2071  /// number of bytes that were not processed.
2072  size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
2073  {return ChannelPut(channel, &inByte, 1, blocking);}
2074 
2075  /// \brief Input a byte buffer for processing on a channel
2076  /// \param channel the channel to process the data
2077  /// \param inString the byte buffer to process
2078  /// \param length the size of the string, in bytes
2079  /// \param blocking specifies whether the object should block when processing input
2080  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2081  /// number of bytes that were not processed.
2082  size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
2083  {return ChannelPut2(channel, inString, length, 0, blocking);}
2084 
2085  /// \brief Input multiple bytes that may be modified by callee on a channel
2086  /// \param channel the channel to process the data.
2087  /// \param inString the byte buffer to process
2088  /// \param length the size of the string, in bytes
2089  /// \param blocking specifies whether the object should block when processing input
2090  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2091  /// number of bytes that were not processed.
2092  size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
2093  {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
2094 
2095  /// \brief Input a 16-bit word for processing on a channel.
2096  /// \param channel the channel to process the data.
2097  /// \param value the 16-bit value to be processed.
2098  /// \param order the ByteOrder of the value to be processed.
2099  /// \param blocking specifies whether the object should block when processing input.
2100  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2101  /// number of bytes that were not processed.
2102  size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2103 
2104  /// \brief Input a 32-bit word for processing on a channel.
2105  /// \param channel the channel to process the data.
2106  /// \param value the 32-bit value to be processed.
2107  /// \param order the ByteOrder of the value to be processed.
2108  /// \param blocking specifies whether the object should block when processing input.
2109  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2110  /// number of bytes that were not processed.
2111  size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2112 
2113  /// \brief Signal the end of a message
2114  /// \param channel the channel to process the data.
2115  /// \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed
2116  /// \param blocking specifies whether the object should block when processing input
2117  /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
2118  /// number of bytes that were not processed.
2119  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2120  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2121  bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
2122  {return !!ChannelPut2(channel, NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
2123 
2124  /// \brief Input multiple bytes for processing and signal the end of a message
2125  /// \param channel the channel to process the data.
2126  /// \param inString the byte buffer to process
2127  /// \param length the size of the string, in bytes
2128  /// \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed
2129  /// \param blocking specifies whether the object should block when processing input
2130  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2131  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2132  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2133  size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
2134  {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
2135 
2136  /// \brief Request space which can be written into by the caller
2137  /// \param channel the channel to process the data
2138  /// \param size the requested size of the buffer
2139  /// \return a pointer to a memory block with length size
2140  /// \details The purpose of this method is to help avoid extra memory allocations.
2141  /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
2142  /// size is the requested size of the buffer. When the call returns, size is the size of
2143  /// the array returned to the caller.
2144  /// \details The base class implementation sets size to 0 and returns NULL.
2145  /// \note Some objects, like ArraySink(), cannot create a space because its fixed. In the case of
2146  /// an ArraySink(), the pointer to the array is returned and the size is remaining size.
2147  virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
2148 
2149  /// \brief Input multiple bytes for processing on a channel.
2150  /// \param channel the channel to process the data.
2151  /// \param inString the byte buffer to process.
2152  /// \param length the size of the string, in bytes.
2153  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
2154  /// \param blocking specifies whether the object should block when processing input.
2155  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2156  virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
2157 
2158  /// \brief Input multiple bytes that may be modified by callee on a channel
2159  /// \param channel the channel to process the data
2160  /// \param inString the byte buffer to process
2161  /// \param length the size of the string, in bytes
2162  /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
2163  /// \param blocking specifies whether the object should block when processing input
2164  /// \return the number of bytes that remain in the block (i.e., bytes not processed)
2165  virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
2166 
2167  /// \brief Flush buffered input and/or output on a channel
2168  /// \param channel the channel to flush the data
2169  /// \param hardFlush is used to indicate whether all data should be flushed
2170  /// \param propagation the number of attached transformations the ChannelFlush() signal should be passed
2171  /// \param blocking specifies whether the object should block when processing input
2172  /// \return true of the Flush was successful
2173  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2174  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2175  virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
2176 
2177  /// \brief Marks the end of a series of messages on a channel
2178  /// \param channel the channel to signal the end of a series of messages
2179  /// \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed
2180  /// \param blocking specifies whether the object should block when processing input
2181  /// \details Each object that receives the signal will perform its processing, decrement
2182  /// propagation, and then pass the signal on to attached transformations if the value is not 0.
2183  /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
2184  /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
2185  /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
2186  virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
2187 
2188  /// \brief Sets the default retrieval channel
2189  /// \param channel the channel to signal the end of a series of messages
2190  /// \note this function may not be implemented in all objects that should support it.
2191  virtual void SetRetrievalChannel(const std::string &channel);
2192  //@}
2193 
2194  /// \name ATTACHMENT
2195  /// \details Some BufferedTransformation objects (e.g. Filter objects) allow other BufferedTransformation objects to be
2196  /// attached. When this is done, the first object instead of buffering its output, sends that output to the attached
2197  /// object as input. The entire attachment chain is deleted when the anchor object is destructed.
2198 
2199  //@{
2200  /// \brief Determines whether the object allows attachment
2201  /// \return true if the object allows an attachment, false otherwise
2202  /// \details Sources and Filters will returns true, while Sinks and other objects will return false.
2203  virtual bool Attachable() {return false;}
2204 
2205  /// \brief Returns the object immediately attached to this object
2206  /// \return the attached transformation
2207  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2208  /// version of AttachedTransformation() always returns NULL.
2209  virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;}
2210 
2211  /// \brief Returns the object immediately attached to this object
2212  /// \return the attached transformation
2213  /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
2214  /// version of AttachedTransformation() always returns NULL.
2216  {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
2217 
2218  /// \brief Delete the current attachment chain and attach a new one
2219  /// \param newAttachment the new BufferedTransformation to attach
2220  /// \throws NotImplemented
2221  /// \details Detach() deletes the current attachment chain and replace it with an optional newAttachment
2222  /// \details If a derived class does not override Detach(), then the base class throws
2223  /// NotImplemented.
2224  virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) {
2225  CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable());
2226  throw NotImplemented("BufferedTransformation: this object is not attachable");
2227  }
2228 
2229  /// \brief Add newAttachment to the end of attachment chain
2230  /// \param newAttachment the attachment to add to the end of the chain
2231  virtual void Attach(BufferedTransformation *newAttachment);
2232  //@}
2233 
2234 protected:
2235  /// \brief Decrements the propagation count while clamping at 0
2236  /// \return the decremented propagation or 0
2237  static int DecrementPropagation(int propagation)
2238  {return propagation != 0 ? propagation - 1 : 0;}
2239 
2240 private:
2241  byte m_buf[4]; // for ChannelPutWord16 and ChannelPutWord32, to ensure buffer isn't deallocated before non-blocking operation completes
2242 };
2243 
2244 /// \brief An input discarding BufferedTransformation
2245 /// \return a reference to a BufferedTransformation object that discards all input
2246 CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
2247 
2248 /// \brief Interface for crypto material, such as public and private keys, and crypto parameters
2249 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
2250 {
2251 public:
2252  /// Exception thrown when invalid crypto material is detected
2253  class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
2254  {
2255  public:
2256  explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
2257  };
2258 
2259  virtual ~CryptoMaterial() {}
2260 
2261  /// \brief Assign values to this object
2262  /// \details This function can be used to create a public key from a private key.
2263  virtual void AssignFrom(const NameValuePairs &source) =0;
2264 
2265  /// \brief Check this object for errors
2266  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2267  /// \param level the level of thoroughness
2268  /// \returns true if the tests succeed, false otherwise
2269  /// \details There are four levels of thoroughness:
2270  /// <ul>
2271  /// <li>0 - using this object won't cause a crash or exception
2272  /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
2273  /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
2274  /// <li>3 - perform reasonable security checks, and do checks that may take a long time
2275  /// </ul>
2276  /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
2277  /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
2278  /// \sa ThrowIfInvalid()
2279  virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
2280 
2281  /// \brief Check this object for errors
2282  /// \param rng a RandomNumberGenerator for objects which use randomized testing
2283  /// \param level the level of thoroughness
2284  /// \throws InvalidMaterial
2285  /// \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial() if validation fails.
2286  /// \sa Validate()
2287  virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
2288  {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
2289 
2290  /// \brief Saves a key to a BufferedTransformation
2291  /// \param bt the destination BufferedTransformation
2292  /// \throws NotImplemented
2293  /// \details Save() writes the material to a BufferedTransformation.
2294  /// \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
2295  /// includes an object identifier with an algorthm id, like a subjectPublicKeyInfo.
2296  /// \details A "raw" key without the "key info" can be saved using a key's DEREncode() method.
2297  /// \details If a derived class does not override Save(), then the base class throws
2298  /// NotImplemented().
2299  virtual void Save(BufferedTransformation &bt) const
2300  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
2301 
2302  /// \brief Loads a key from a BufferedTransformation
2303  /// \param bt the source BufferedTransformation
2304  /// \throws KeyingErr
2305  /// \details Load() attempts to read material from a BufferedTransformation. If the
2306  /// material is a key that was generated outside the library, then the following
2307  /// usually applies:
2308  /// <ul>
2309  /// <li>the key should be ASN.1 BER encoded
2310  /// <li>the key should be a "key info"
2311  /// </ul>
2312  /// \details "key info" means the key should have an object identifier with an algorthm id,
2313  /// like a subjectPublicKeyInfo.
2314  /// \details To read a "raw" key without the "key info", then call the key's BERDecode() method.
2315  /// \note Load() generally does not check that the key is valid. Call Validate(), if needed.
2316  virtual void Load(BufferedTransformation &bt)
2317  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
2318 
2319  /// \brief Determines whether the object supports precomputation
2320  /// \return true if the object supports precomputation, false otherwise
2321  /// \sa Precompute()
2322  virtual bool SupportsPrecomputation() const {return false;}
2323 
2324  /// \brief Perform precomputation
2325  /// \param precomputationStorage the suggested number of objects for the precompute table
2326  /// \throws NotImplemented
2327  /// \details The exact semantics of Precompute() varies, but it typically means calculate
2328  /// a table of n objects that can be used later to speed up computation.
2329  /// \details If a derived class does not override Precompute(), then the base class throws
2330  /// NotImplemented.
2331  /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation()
2332  virtual void Precompute(unsigned int precomputationStorage) {
2333  CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation());
2334  throw NotImplemented("CryptoMaterial: this object does not support precomputation");
2335  }
2336 
2337  /// \brief Retrieve previously saved precomputation
2338  /// \param storedPrecomputation BufferedTransformation with the saved precomputation
2339  /// \throws NotImplemented
2340  /// \sa SupportsPrecomputation(), Precompute()
2341  virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
2342  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2343 
2344  /// \brief Save precomputation for later use
2345  /// \param storedPrecomputation BufferedTransformation to write the precomputation
2346  /// \throws NotImplemented
2347  /// \sa SupportsPrecomputation(), Precompute()
2348  virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
2349  {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2350 
2351  /// \brief Perform a quick sanity check
2352  /// \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users.
2353  void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
2354 
2355 #if defined(__SUNPRO_CC)
2356  // Sun Studio 11/CC 5.8 workaround: it generates incorrect code
2357  // when casting to an empty virtual base class. JW, 2018: It is
2358  // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable
2359  // it everywhere in case it affects SPARC (which we don't test).
2360  char m_sunCCworkaround;
2361 #endif
2362 };
2363 
2364 /// \brief Interface for generatable crypto material, such as private keys and crypto parameters
2365 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
2366 {
2367 public:
2368  virtual ~GeneratableCryptoMaterial() {}
2369 
2370  /// \brief Generate a random key or crypto parameters
2371  /// \param rng a RandomNumberGenerator to produce keying material
2372  /// \param params additional initialization parameters
2373  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2374  /// \details If a derived class does not override GenerateRandom(), then the base class throws
2375  /// NotImplemented.
2377  CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
2378  throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
2379  }
2380 
2381  /// \brief Generate a random key or crypto parameters
2382  /// \param rng a RandomNumberGenerator to produce keying material
2383  /// \param keySize the size of the key, in bits
2384  /// \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2385  /// \details GenerateRandomWithKeySize calls GenerateRandom() with a NameValuePairs
2386  /// object with only "KeySize"
2387  void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
2388 };
2389 
2390 /// \brief Interface for public keys
2391 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
2392 {
2393 };
2394 
2395 /// \brief Interface for private keys
2396 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
2397 {
2398 };
2399 
2400 /// \brief Interface for crypto prameters
2401 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
2402 {
2403 };
2404 
2405 /// \brief Interface for asymmetric algorithms
2406 /// \details BERDecode() and DEREncode() were removed under Issue 569
2407 /// and Commit 9b174e84de7a. Programs should use <tt>AccessMaterial().Load(bt)</tt>
2408 /// or <tt>AccessMaterial().Save(bt)</tt> instead.
2409 /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/569">Issue 569</A>
2410 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
2411 {
2412 public:
2413  virtual ~AsymmetricAlgorithm() {}
2414 
2415  /// \brief Retrieves a reference to CryptoMaterial
2416  /// \return a reference to the crypto material
2417  virtual CryptoMaterial & AccessMaterial() =0;
2418 
2419  /// \brief Retrieves a reference to CryptoMaterial
2420  /// \return a const reference to the crypto material
2421  virtual const CryptoMaterial & GetMaterial() const =0;
2422 
2423 #if 0
2424  /// \brief Loads this object from a BufferedTransformation
2425  /// \param bt a BufferedTransformation object
2426  /// \details Use of BERDecode() changed to Load() at Issue 569.
2427  /// \deprecated for backwards compatibility, calls <tt>AccessMaterial().Load(bt)</tt>
2428  void BERDecode(BufferedTransformation &bt)
2429  {AccessMaterial().Load(bt);}
2430 
2431  /// \brief Saves this object to a BufferedTransformation
2432  /// \param bt a BufferedTransformation object
2433  /// \details Use of DEREncode() changed to Save() at Issue 569.
2434  /// \deprecated for backwards compatibility, calls GetMaterial().Save(bt)
2435  void DEREncode(BufferedTransformation &bt) const
2436  {GetMaterial().Save(bt);}
2437 #endif
2438 };
2439 
2440 /// \brief Interface for asymmetric algorithms using public keys
2441 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
2442 {
2443 public:
2444  virtual ~PublicKeyAlgorithm() {}
2445 
2446  // VC60 workaround: no co-variant return type
2447 
2448  /// \brief Retrieves a reference to a Public Key
2449  /// \return a reference to the public key
2451  {return AccessPublicKey();}
2452  /// \brief Retrieves a reference to a Public Key
2453  /// \return a const reference the public key
2454  const CryptoMaterial & GetMaterial() const
2455  {return GetPublicKey();}
2456 
2457  /// \brief Retrieves a reference to a Public Key
2458  /// \return a reference to the public key
2459  virtual PublicKey & AccessPublicKey() =0;
2460  /// \brief Retrieves a reference to a Public Key
2461  /// \return a const reference the public key
2462  virtual const PublicKey & GetPublicKey() const
2463  {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
2464 };
2465 
2466 /// \brief Interface for asymmetric algorithms using private keys
2467 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
2468 {
2469 public:
2470  virtual ~PrivateKeyAlgorithm() {}
2471 
2472  /// \brief Retrieves a reference to a Private Key
2473  /// \return a reference the private key
2474  CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
2475  /// \brief Retrieves a reference to a Private Key
2476  /// \return a const reference the private key
2477  const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
2478 
2479  /// \brief Retrieves a reference to a Private Key
2480  /// \return a reference the private key
2481  virtual PrivateKey & AccessPrivateKey() =0;
2482  /// \brief Retrieves a reference to a Private Key
2483  /// \return a const reference the private key
2484  virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
2485 };
2486 
2487 /// \brief Interface for key agreement algorithms
2488 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
2489 {
2490 public:
2491  virtual ~KeyAgreementAlgorithm() {}
2492 
2493  /// \brief Retrieves a reference to Crypto Parameters
2494  /// \return a reference the crypto parameters
2495  CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
2496  /// \brief Retrieves a reference to Crypto Parameters
2497  /// \return a const reference the crypto parameters
2498  const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
2499 
2500  /// \brief Retrieves a reference to Crypto Parameters
2501  /// \return a reference the crypto parameters
2502  virtual CryptoParameters & AccessCryptoParameters() =0;
2503  /// \brief Retrieves a reference to Crypto Parameters
2504  /// \return a const reference the crypto parameters
2505  virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
2506 };
2507 
2508 /// \brief Interface for public-key encryptors and decryptors
2509 /// \details This class provides an interface common to encryptors and decryptors
2510 /// for querying their plaintext and ciphertext lengths.
2511 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
2512 {
2513 public:
2514  virtual ~PK_CryptoSystem() {}
2515 
2516  /// \brief Provides the maximum length of plaintext for a given ciphertext length
2517  /// \return the maximum size of the plaintext, in bytes
2518  /// \details This function returns 0 if ciphertextLength is not valid (too long or too short).
2519  virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
2520 
2521  /// \brief Calculate the length of ciphertext given length of plaintext
2522  /// \return the maximum size of the ciphertext, in bytes
2523  /// \details This function returns 0 if plaintextLength is not valid (too long).
2524  virtual size_t CiphertextLength(size_t plaintextLength) const =0;
2525 
2526  /// \brief Determines whether this object supports the use of a named parameter
2527  /// \param name the name of the parameter
2528  /// \return true if the parameter name is supported, false otherwise
2529  /// \details Some possible parameter names: EncodingParameters(), KeyDerivationParameters()
2530  /// and others Parameters listed in argnames.h
2531  virtual bool ParameterSupported(const char *name) const =0;
2532 
2533  /// \brief Provides the fixed ciphertext length, if one exists
2534  /// \return the fixed ciphertext length if one exists, otherwise 0
2535  /// \details "Fixed" here means length of ciphertext does not depend on length of plaintext.
2536  /// In this case, it usually does depend on the key length.
2537  virtual size_t FixedCiphertextLength() const {return 0;}
2538 
2539  /// \brief Provides the maximum plaintext length given a fixed ciphertext length
2540  /// \return maximum plaintext length given the fixed ciphertext length, if one exists,
2541  /// otherwise return 0.
2542  /// \details FixedMaxPlaintextLength(0 returns the maximum plaintext length given the fixed ciphertext
2543  /// length, if one exists, otherwise return 0.
2544  virtual size_t FixedMaxPlaintextLength() const {return 0;}
2545 };
2546 
2547 /// \brief Interface for public-key encryptors
2548 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
2549 {
2550 public:
2551  /// \brief Exception thrown when trying to encrypt plaintext of invalid length
2552  class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
2553  {
2554  public:
2555  InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
2556  };
2557 
2558  /// \brief Encrypt a byte string
2559  /// \param rng a RandomNumberGenerator derived class
2560  /// \param plaintext the plaintext byte buffer
2561  /// \param plaintextLength the size of the plaintext byte buffer
2562  /// \param ciphertext a byte buffer to hold the encrypted string
2563  /// \param parameters a set of NameValuePairs to initialize this object
2564  /// \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
2565  /// \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
2566  /// byte buffer is large enough.
2567  /// \sa PK_Decryptor
2568  virtual void Encrypt(RandomNumberGenerator &rng,
2569  const byte *plaintext, size_t plaintextLength,
2570  byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2571 
2572  /// \brief Create a new encryption filter
2573  /// \param rng a RandomNumberGenerator derived class
2574  /// \param attachment an attached transformation
2575  /// \param parameters a set of NameValuePairs to initialize this object
2576  /// \details \p attachment can be \p NULL. The caller is responsible for deleting the returned pointer.
2577  /// Encoding parameters should be passed in the "EP" channel.
2578  virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
2579  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2580 };
2581 
2582 /// \brief Interface for public-key decryptors
2583 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
2584 {
2585 public:
2586  virtual ~PK_Decryptor() {}
2587 
2588  /// \brief Decrypt a byte string
2589  /// \param rng a RandomNumberGenerator derived class
2590  /// \param ciphertext the encrypted byte buffer
2591  /// \param ciphertextLength the size of the encrypted byte buffer
2592  /// \param plaintext a byte buffer to hold the decrypted string
2593  /// \param parameters a set of NameValuePairs to initialize this object
2594  /// \return the result of the decryption operation
2595  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2596  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2597  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2598  /// is undefined.
2599  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2600  /// byte buffer is large enough
2601  /// \sa PK_Encryptor
2602  virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
2603  const byte *ciphertext, size_t ciphertextLength,
2604  byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2605 
2606  /// \brief Create a new decryption filter
2607  /// \param rng a RandomNumberGenerator derived class
2608  /// \param attachment an attached transformation
2609  /// \param parameters a set of NameValuePairs to initialize this object
2610  /// \return the newly created decryption filter
2611  /// \note the caller is responsible for deleting the returned pointer
2612  virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
2613  BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2614 
2615  /// \brief Decrypt a fixed size ciphertext
2616  /// \param rng a RandomNumberGenerator derived class
2617  /// \param ciphertext the encrypted byte buffer
2618  /// \param plaintext a byte buffer to hold the decrypted string
2619  /// \param parameters a set of NameValuePairs to initialize this object
2620  /// \return the result of the decryption operation
2621  /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2622  /// is valid and holds the the actual length of the plaintext recovered. The result is undefined
2623  /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
2624  /// is undefined.
2625  /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2626  /// byte buffer is large enough
2627  /// \sa PK_Encryptor
2628  DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
2629  {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
2630 };
2631 
2632 /// \brief Interface for public-key signers and verifiers
2633 /// \details This class provides an interface common to signers and verifiers for querying scheme properties
2634 /// \sa DL_SignatureSchemeBase, TF_SignatureSchemeBase, DL_SignerBase, TF_SignerBase
2635 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
2636 {
2637 public:
2638  /// \brief Exception throw when the private or public key has a length that can't be used
2639  /// \details InvalidKeyLength() may be thrown by any function in this class if the private
2640  /// or public key has a length that can't be used
2641  class CRYPTOPP_DLL InvalidKeyLength : public Exception
2642  {
2643  public:
2644  InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
2645  };
2646 
2647  /// \brief Exception throw when the private or public key is too short to sign or verify
2648  /// \details KeyTooShort() may be thrown by any function in this class if the private or public
2649  /// key is too short to sign or verify anything
2650  class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
2651  {
2652  public:
2653  KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
2654  };
2655 
2656  virtual ~PK_SignatureScheme() {}
2657 
2658  /// \brief Provides the signature length if it only depends on the key
2659  /// \return the signature length if it only depends on the key, in bytes
2660  /// \details SignatureLength() returns the signature length if it only depends on the key, otherwise 0.
2661  virtual size_t SignatureLength() const =0;
2662 
2663  /// \brief Provides the maximum signature length produced given the length of the recoverable message part
2664  /// \param recoverablePartLength the length of the recoverable message part, in bytes
2665  /// \return the maximum signature length produced for a given length of recoverable message part, in bytes
2666  /// \details MaxSignatureLength() returns the maximum signature length produced given the length of the
2667  /// recoverable message part.
2668  virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
2669  {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
2670 
2671  /// \brief Provides the length of longest message that can be recovered
2672  /// \return the length of longest message that can be recovered, in bytes
2673  /// \details MaxRecoverableLength() returns the length of longest message that can be recovered, or 0 if
2674  /// this signature scheme does not support message recovery.
2675  virtual size_t MaxRecoverableLength() const =0;
2676 
2677  /// \brief Provides the length of longest message that can be recovered from a signature of given length
2678  /// \param signatureLength the length of the signature, in bytes
2679  /// \return the length of longest message that can be recovered from a signature of given length, in bytes
2680  /// \details MaxRecoverableLengthFromSignatureLength() returns the length of longest message that can be
2681  /// recovered from a signature of given length, or 0 if this signature scheme does not support message
2682  /// recovery.
2683  virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
2684 
2685  /// \brief Determines whether a signature scheme requires a random number generator
2686  /// \return true if the signature scheme requires a RandomNumberGenerator() to sign
2687  /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take
2688  /// RandomNumberGenerator().
2689  virtual bool IsProbabilistic() const =0;
2690 
2691  /// \brief Determines whether the non-recoverable message part can be signed
2692  /// \return true if the non-recoverable message part can be signed
2693  virtual bool AllowNonrecoverablePart() const =0;
2694 
2695  /// \brief Determines whether the signature must be input before the message
2696  /// \return true if the signature must be input before the message during verifcation
2697  /// \details if SignatureUpfront() returns true, then you must input the signature before the message
2698  /// during verification. Otherwise you can input the signature at anytime.
2699  virtual bool SignatureUpfront() const {return false;}
2700 
2701  /// \brief Determines whether the recoverable part must be input before the non-recoverable part
2702  /// \return true if the recoverable part must be input before the non-recoverable part during signing
2703  /// \details RecoverablePartFirst() determines whether you must input the recoverable part before the
2704  /// non-recoverable part during signing
2705  virtual bool RecoverablePartFirst() const =0;
2706 };
2707 
2708 /// \brief Interface for accumulating messages to be signed or verified
2709 /// \details Only Update() should be called from the PK_MessageAccumulator() class. No other functions
2710 /// inherited from HashTransformation, like DigestSize() and TruncatedFinal(), should be called.
2711 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
2712 {
2713 public:
2714  /// \warning DigestSize() should not be called on PK_MessageAccumulator
2715  unsigned int DigestSize() const
2716  {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
2717 
2718  /// \warning TruncatedFinal() should not be called on PK_MessageAccumulator
2719  void TruncatedFinal(byte *digest, size_t digestSize)
2720  {
2721  CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
2722  throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
2723  }
2724 };
2725 
2726 /// \brief Interface for public-key signers
2727 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
2728 {
2729 public:
2730  virtual ~PK_Signer() {}
2731 
2732  /// \brief Create a new HashTransformation to accumulate the message to be signed
2733  /// \param rng a RandomNumberGenerator derived class
2734  /// \return a pointer to a PK_MessageAccumulator
2735  /// \details NewSignatureAccumulator() can be used with all signing methods. Sign() will autimatically delete the
2736  /// accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2737  virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
2738 
2739  /// \brief Input a recoverable message to an accumulator
2740  /// \param messageAccumulator a reference to a PK_MessageAccumulator
2741  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2742  /// \param recoverableMessageLength the size of the recoverable message part
2743  virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
2744 
2745  /// \brief Sign and delete the messageAccumulator
2746  /// \param rng a RandomNumberGenerator derived class
2747  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2748  /// \param signature a block of bytes for the signature
2749  /// \return actual signature length
2750  /// \details Sign() deletes the messageAccumulator, even if an exception is thrown.
2751  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2752  virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
2753 
2754  /// \brief Sign and restart messageAccumulator
2755  /// \param rng a RandomNumberGenerator derived class
2756  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2757  /// \param signature a block of bytes for the signature
2758  /// \param restart flag indicating whether the messageAccumulator should be restarted
2759  /// \return actual signature length
2760  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2761  virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
2762 
2763  /// \brief Sign a message
2764  /// \param rng a RandomNumberGenerator derived class
2765  /// \param message a pointer to the message
2766  /// \param messageLen the size of the message to be signed
2767  /// \param signature a block of bytes for the signature
2768  /// \return actual signature length
2769  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
2770  virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
2771 
2772  /// \brief Sign a recoverable message
2773  /// \param rng a RandomNumberGenerator derived class
2774  /// \param recoverableMessage a pointer to the recoverable message part to be signed
2775  /// \param recoverableMessageLength the size of the recoverable message part
2776  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2777  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2778  /// \param signature a block of bytes for the signature
2779  /// \return actual signature length
2780  /// \pre <tt>COUNTOF(signature) == MaxSignatureLength(recoverableMessageLength)</tt>
2781  virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
2782  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
2783 };
2784 
2785 /// \brief Interface for public-key signature verifiers
2786 /// \details The Recover* functions throw NotImplemented if the signature scheme does not support
2787 /// message recovery.
2788 /// \details The Verify* functions throw InvalidDataFormat if the scheme does support message
2789 /// recovery and the signature contains a non-empty recoverable message part. The
2790 /// Recover* functions should be used in that case.
2791 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
2792 {
2793 public:
2794  virtual ~PK_Verifier() {}
2795 
2796  /// \brief Create a new HashTransformation to accumulate the message to be verified
2797  /// \return a pointer to a PK_MessageAccumulator
2798  /// \details NewVerificationAccumulator() can be used with all verification methods. Verify() will autimatically delete
2799  /// the accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
2800  virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
2801 
2802  /// \brief Input signature into a message accumulator
2803  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2804  /// \param signature the signature on the message
2805  /// \param signatureLength the size of the signature
2806  virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
2807 
2808  /// \brief Check whether messageAccumulator contains a valid signature and message
2809  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2810  /// \return true if the signature is valid, false otherwise
2811  /// \details Verify() deletes the messageAccumulator, even if an exception is thrown.
2812  virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
2813 
2814  /// \brief Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
2815  /// \param messageAccumulator a reference to a PK_MessageAccumulator derived class
2816  /// \return true if the signature is valid, false otherwise
2817  /// \details VerifyAndRestart() restarts the messageAccumulator
2818  virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
2819 
2820  /// \brief Check whether input signature is a valid signature for input message
2821  /// \param message a pointer to the message to be verified
2822  /// \param messageLen the size of the message
2823  /// \param signature a pointer to the signature over the message
2824  /// \param signatureLen the size of the signature
2825  /// \return true if the signature is valid, false otherwise
2826  virtual bool VerifyMessage(const byte *message, size_t messageLen,
2827  const byte *signature, size_t signatureLen) const;
2828 
2829  /// \brief Recover a message from its signature
2830  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2831  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2832  /// \return the result of the verification operation
2833  /// \details Recover() deletes the messageAccumulator, even if an exception is thrown.
2834  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2835  virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
2836 
2837  /// \brief Recover a message from its signature
2838  /// \param recoveredMessage a pointer to the recoverable message part to be verified
2839  /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
2840  /// \return the result of the verification operation
2841  /// \details RecoverAndRestart() restarts the messageAccumulator
2842  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2843  virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
2844 
2845  /// \brief Recover a message from its signature
2846  /// \param recoveredMessage a pointer for the recovered message
2847  /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
2848  /// \param nonrecoverableMessageLength the size of the non-recoverable message part
2849  /// \param signature the signature on the message
2850  /// \param signatureLength the size of the signature
2851  /// \return the result of the verification operation
2852  /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
2853  virtual DecodingResult RecoverMessage(byte *recoveredMessage,
2854  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
2855  const byte *signature, size_t signatureLength) const;
2856 };
2857 
2858 /// \brief Interface for domains of simple key agreement protocols
2859 /// \details A key agreement domain is a set of parameters that must be shared
2860 /// by two parties in a key agreement protocol, along with the algorithms
2861 /// for generating key pairs and deriving agreed values.
2862 /// \since Crypto++ 3.0
2863 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
2864 {
2865 public:
2866  virtual ~SimpleKeyAgreementDomain() {}
2867 
2868  /// \brief Provides the size of the agreed value
2869  /// \return size of agreed value produced in this domain
2870  virtual unsigned int AgreedValueLength() const =0;
2871 
2872  /// \brief Provides the size of the private key
2873  /// \return size of private keys in this domain
2874  virtual unsigned int PrivateKeyLength() const =0;
2875 
2876  /// \brief Provides the size of the public key
2877  /// \return size of public keys in this domain
2878  virtual unsigned int PublicKeyLength() const =0;
2879 
2880  /// \brief Generate private key in this domain
2881  /// \param rng a RandomNumberGenerator derived class
2882  /// \param privateKey a byte buffer for the generated private key in this domain
2883  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
2884  virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
2885 
2886  /// \brief Generate a public key from a private key in this domain
2887  /// \param rng a RandomNumberGenerator derived class
2888  /// \param privateKey a byte buffer with the previously generated private key
2889  /// \param publicKey a byte buffer for the generated public key in this domain
2890  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
2891  virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
2892 
2893  /// \brief Generate a private/public key pair
2894  /// \param rng a RandomNumberGenerator derived class
2895  /// \param privateKey a byte buffer for the generated private key in this domain
2896  /// \param publicKey a byte buffer for the generated public key in this domain
2897  /// \details GenerateKeyPair() is equivalent to calling GeneratePrivateKey() and then GeneratePublicKey().
2898  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
2899  /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
2900  virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
2901 
2902  /// \brief Derive agreed value
2903  /// \param agreedValue a byte buffer for the shared secret
2904  /// \param privateKey a byte buffer with your private key in this domain
2905  /// \param otherPublicKey a byte buffer with the other party's public key in this domain
2906  /// \param validateOtherPublicKey a flag indicating if the other party's public key should be validated
2907  /// \return true upon success, false in case of failure
2908  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
2909  /// \details The other party's public key is validated by default. If you have previously validated the
2910  /// static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
2911  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
2912  /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
2913  /// \pre <tt>COUNTOF(otherPublicKey) == PublicKeyLength()</tt>
2914  virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
2915 };
2916 
2917 /// \brief Interface for domains of authenticated key agreement protocols
2918 /// \details In an authenticated key agreement protocol, each party has two
2919 /// key pairs. The long-lived key pair is called the static key pair,
2920 /// and the short-lived key pair is called the ephemeral key pair.
2921 /// \since Crypto++ 3.0
2922 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
2923 {
2924 public:
2925  virtual ~AuthenticatedKeyAgreementDomain() {}
2926 
2927  /// \brief Provides the size of the agreed value
2928  /// \return size of agreed value produced in this domain
2929  virtual unsigned int AgreedValueLength() const =0;
2930 
2931  /// \brief Provides the size of the static private key
2932  /// \return size of static private keys in this domain
2933  virtual unsigned int StaticPrivateKeyLength() const =0;
2934 
2935  /// \brief Provides the size of the static public key
2936  /// \return size of static public keys in this domain
2937  virtual unsigned int StaticPublicKeyLength() const =0;
2938 
2939  /// \brief Generate static private key in this domain
2940  /// \param rng a RandomNumberGenerator derived class
2941  /// \param privateKey a byte buffer for the generated private key in this domain
2942  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
2943  virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
2944 
2945  /// \brief Generate a static public key from a private key in this domain
2946  /// \param rng a RandomNumberGenerator derived class
2947  /// \param privateKey a byte buffer with the previously generated private key
2948  /// \param publicKey a byte buffer for the generated public key in this domain
2949  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
2950  virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
2951 
2952  /// \brief Generate a static private/public key pair
2953  /// \param rng a RandomNumberGenerator derived class
2954  /// \param privateKey a byte buffer for the generated private key in this domain
2955  /// \param publicKey a byte buffer for the generated public key in this domain
2956  /// \details GenerateStaticKeyPair() is equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey().
2957  /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
2958  /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
2959  virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
2960 
2961  /// \brief Provides the size of ephemeral private key
2962  /// \return the size of ephemeral private key in this domain
2963  virtual unsigned int EphemeralPrivateKeyLength() const =0;
2964 
2965  /// \brief Provides the size of ephemeral public key
2966  /// \return the size of ephemeral public key in this domain
2967  virtual unsigned int EphemeralPublicKeyLength() const =0;
2968 
2969  /// \brief Generate ephemeral private key
2970  /// \param rng a RandomNumberGenerator derived class
2971  /// \param privateKey a byte buffer for the generated private key in this domain
2972  /// \pre <tt>COUNTOF(privateKey) == PrivateEphemeralKeyLength()</tt>
2973  virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
2974 
2975  /// \brief Generate ephemeral public key
2976  /// \param rng a RandomNumberGenerator derived class
2977  /// \param privateKey a byte buffer for the generated private key in this domain
2978  /// \param publicKey a byte buffer for the generated public key in this domain
2979  /// \pre <tt>COUNTOF(publicKey) == PublicEphemeralKeyLength()</tt>
2980  virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
2981 
2982  /// \brief Generate private/public key pair
2983  /// \param rng a RandomNumberGenerator derived class
2984  /// \param privateKey a byte buffer for the generated private key in this domain
2985  /// \param publicKey a byte buffer for the generated public key in this domain
2986  /// \details GenerateEphemeralKeyPair() is equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey()
2987  virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
2988 
2989  /// \brief Derive agreed value
2990  /// \param agreedValue a byte buffer for the shared secret
2991  /// \param staticPrivateKey a byte buffer with your static private key in this domain
2992  /// \param ephemeralPrivateKey a byte buffer with your ephemeral private key in this domain
2993  /// \param staticOtherPublicKey a byte buffer with the other party's static public key in this domain
2994  /// \param ephemeralOtherPublicKey a byte buffer with the other party's ephemeral public key in this domain
2995  /// \param validateStaticOtherPublicKey a flag indicating if the other party's public key should be validated
2996  /// \return true upon success, false in case of failure
2997  /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
2998  /// \details The other party's ephemeral public key is validated by default. If you have previously validated
2999  /// the static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
3000  /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
3001  /// \pre <tt>COUNTOF(staticPrivateKey) == StaticPrivateKeyLength()</tt>
3002  /// \pre <tt>COUNTOF(ephemeralPrivateKey) == EphemeralPrivateKeyLength()</tt>
3003  /// \pre <tt>COUNTOF(staticOtherPublicKey) == StaticPublicKeyLength()</tt>
3004  /// \pre <tt>COUNTOF(ephemeralOtherPublicKey) == EphemeralPublicKeyLength()</tt>
3005  virtual bool Agree(byte *agreedValue,
3006  const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
3007  const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
3008  bool validateStaticOtherPublicKey=true) const =0;
3009 };
3010 
3011 // interface for password authenticated key agreement protocols, not implemented yet
3012 #if 0
3013 /// \brief Interface for protocol sessions
3014 /*! The methods should be called in the following order:
3015 
3016  InitializeSession(rng, parameters); // or call initialize method in derived class
3017  while (true)
3018  {
3019  if (OutgoingMessageAvailable())
3020  {
3021  length = GetOutgoingMessageLength();
3022  GetOutgoingMessage(message);
3023  ; // send outgoing message
3024  }
3025 
3026  if (LastMessageProcessed())
3027  break;
3028 
3029  ; // receive incoming message
3030  ProcessIncomingMessage(message);
3031  }
3032  ; // call methods in derived class to obtain result of protocol session
3033 */
3034 class ProtocolSession
3035 {
3036 public:
3037  /// Exception thrown when an invalid protocol message is processed
3038  class ProtocolError : public Exception
3039  {
3040  public:
3041  ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
3042  };
3043 
3044  /// Exception thrown when a function is called unexpectedly
3045  /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
3046  class UnexpectedMethodCall : public Exception
3047  {
3048  public:
3049  UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
3050  };
3051 
3052  virtual ~ProtocolSession() {}
3053 
3054  ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {}
3055 
3056  virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
3057 
3058  bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
3059  void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
3060 
3061  bool HasValidState() const {return m_validState;}
3062 
3063  virtual bool OutgoingMessageAvailable() const =0;
3064  virtual unsigned int GetOutgoingMessageLength() const =0;
3065  virtual void GetOutgoingMessage(byte *message) =0;
3066 
3067  virtual bool LastMessageProcessed() const =0;
3068  virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
3069 
3070 protected:
3071  void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
3072  void CheckAndHandleInvalidState() const;
3073  void SetValidState(bool valid) {m_validState = valid;}
3074 
3075  RandomNumberGenerator *m_rng;
3076 
3077 private:
3078  bool m_throwOnProtocolError, m_validState;
3079 };
3080 
3081 class KeyAgreementSession : public ProtocolSession
3082 {
3083 public:
3084  virtual ~KeyAgreementSession() {}
3085 
3086  virtual unsigned int GetAgreedValueLength() const =0;
3087  virtual void GetAgreedValue(byte *agreedValue) const =0;
3088 };
3089 
3090 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
3091 {
3092 public:
3093  virtual ~PasswordAuthenticatedKeyAgreementSession() {}
3094 
3095  void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
3096  const byte *myId, unsigned int myIdLength,
3097  const byte *counterPartyId, unsigned int counterPartyIdLength,
3098  const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
3099 };
3100 
3101 /// \brief Password based key agreement domain
3102 /// \since Crypto++ 3.0
3103 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3104 {
3105 public:
3106  virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
3107 
3108  /// return whether the domain parameters stored in this object are valid
3109  virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
3110  {return GetCryptoParameters().Validate(rng, 2);}
3111 
3112  virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
3113  virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
3114 
3115  enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
3116 
3117  virtual bool IsValidRole(unsigned int role) =0;
3118  virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
3119 };
3120 #endif
3121 
3122 /// \brief Exception thrown when an ASN.1 BER decoing error is encountered
3123 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
3124 {
3125 public:
3126  BERDecodeErr() : InvalidArgument("BER decode error") {}
3127  BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
3128 };
3129 
3130 /// \brief Interface for encoding and decoding ASN1 objects
3131 /// \details Each class that derives from ASN1Object should provide a serialization format
3132 /// that controls subobject layout. Most of the time the serialization format is
3133 /// taken from a standard, like P1363 or an RFC.
3134 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
3135 {
3136 public:
3137  virtual ~ASN1Object() {}
3138 
3139  /// \brief Decode this object from a BufferedTransformation
3140  /// \param bt BufferedTransformation object
3141  /// \details Uses Basic Encoding Rules (BER)
3142  virtual void BERDecode(BufferedTransformation &bt) =0;
3143 
3144  /// \brief Encode this object into a BufferedTransformation
3145  /// \param bt BufferedTransformation object
3146  /// \details Uses Distinguished Encoding Rules (DER)
3147  virtual void DEREncode(BufferedTransformation &bt) const =0;
3148 
3149  /// \brief Encode this object into a BufferedTransformation
3150  /// \param bt BufferedTransformation object
3151  /// \details Uses Basic Encoding Rules (BER).
3152  /// \details This may be useful if DEREncode() would be too inefficient.
3153  virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
3154 };
3155 
3156 /// \brief Specifies the build-time version of the library
3157 /// \returns integer representing the build-time version
3158 /// \details LibraryVersion can help detect inadvertent mixing and matching of library
3159 /// versions. When using Crypto++ distributed by a third party, LibraryVersion()
3160 /// records the version of the shared object that was built by the third party.
3161 /// The LibraryVersion() record resides in <tt>cryptlib.o</tt> on Unix compatibles
3162 /// and <tt>cryptlib.obj</tt> on Windows. It does not change when an app links
3163 /// to the library.
3164 /// \details LibraryVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3165 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3166 /// the library version is 5.7 or above. If it is missing, then the library version is
3167 /// 5.6.5 or below.
3168 /// \details The function could be used as shown below.
3169 /// <pre>
3170 /// if (LibraryVersion() != HeaderVersion())
3171 /// {
3172 /// cout << "Potential version mismatch" << endl;
3173 ///
3174 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3175 /// const int lmin = (LibraryVersion() / 10U) % 10;
3176 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3177 /// const int hmin = (HeaderVersion() / 10U) % 10;
3178 ///
3179 /// if(lmaj != hmaj)
3180 /// cout << "Major version mismatch" << endl;
3181 /// else if(lmin != hmin)
3182 /// cout << "Minor version mismatch" << endl;
3183 /// }
3184 /// </pre>
3185 /// \sa HeaderVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3186 /// \since Crypto++ 6.0
3187 extern "C" {
3188  int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT);
3189 } // C linkage
3190 
3191 /// \brief Specifies the runtime version of the library
3192 /// \returns integer representing the runtime version
3193 /// \details HeaderVersion() can help detect inadvertent mixing and matching of library
3194 /// versions. When using Crypto++ distributed by a third party, HeaderVersion()
3195 /// records the version of the headers used by the app when the app is compiled.
3196 /// \details HeaderVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
3197 /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
3198 /// the library version is 5.7 or above. If it is missing, then the library version is
3199 /// 5.6.5 or below.
3200 /// \details The function could be used as shown below.
3201 /// <pre>
3202 /// if (LibraryVersion() != HeaderVersion())
3203 /// {
3204 /// cout << "Potential version mismatch" << endl;
3205 ///
3206 /// const int lmaj = (LibraryVersion() / 100U) % 10;
3207 /// const int lmin = (LibraryVersion() / 10U) % 10;
3208 /// const int hmaj = (HeaderVersion() / 100U) % 10;
3209 /// const int hmin = (HeaderVersion() / 10U) % 10;
3210 ///
3211 /// if(lmaj != hmaj)
3212 /// cout << "Major version mismatch" << endl;
3213 /// else if(lmin != hmin)
3214 /// cout << "Minor version mismatch" << endl;
3215 /// }
3216 /// </pre>
3217 /// \sa LibraryVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
3218 /// \since Crypto++ 6.0
3219 extern "C" {
3220 inline int HeaderVersion()
3221 {
3222  return CRYPTOPP_VERSION;
3223 }
3224 } // C linkage
3225 
3226 NAMESPACE_END
3227 
3228 #if CRYPTOPP_MSC_VERSION
3229 # pragma warning(pop)
3230 #endif
3231 
3232 #endif
virtual unsigned int BlockSize() const
Provides the block size of the compression function.
Definition: cryptlib.h:1135
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:158
int HeaderVersion()
Specifies the runtime version of the library.
Definition: cryptlib.h:3220
Exception thrown when invalid crypto material is detected.
Definition: cryptlib.h:2253
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition: cryptlib.h:2332
int GetIntValueWithDefault(const char *name, int defaultValue) const
Get a named value with type int, with default.
Definition: cryptlib.h:395
the cipher is performing decryption
Definition: cryptlib.h:127
const char * DigestSize()
int, in bytes
Definition: argnames.h:79
An invalid argument was detected.
Definition: cryptlib.h:202
void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
Sets or reset the key of this object.
Definition: cryptlib.h:680
unsigned int TagSize() const
Provides the tag size of the hash.
Definition: cryptlib.h:1129
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:1461
Interface for message authentication codes.
Definition: cryptlib.h:1264
ErrorType
Error types or categories.
Definition: cryptlib.h:163
Interface for asymmetric algorithms.
Definition: cryptlib.h:2410
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition: cryptlib.h:743
Namespace containing NaCl library functions.
Definition: cryptlib.h:540
virtual bool NeedsPrespecifiedDataLengths() const
Determines if data lengths must be specified prior to inputting data.
Definition: cryptlib.h:1315
Interface for public-key encryptors and decryptors.
Definition: cryptlib.h:2511
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:143
const char * what() const
Retrieves a C-string describing the exception.
Definition: cryptlib.h:186
virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: cryptlib.h:2287
The IV is set by the object.
Definition: cryptlib.h:699
The operating system reported an error.
Definition: cryptlib.h:237
Interface for authenticated encryption modes of operation.
Definition: cryptlib.h:1286
T GetValueWithDefault(const char *name, T defaultValue) const
Get a named value.
Definition: cryptlib.h:363
const std::type_info & GetStoredTypeInfo() const
Provides the stored type.
Definition: cryptlib.h:313
virtual void Load(BufferedTransformation &bt)
Loads a key from a BufferedTransformation.
Definition: cryptlib.h:2316
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition: cryptlib.h:2072
Exception(ErrorType errorType, const std::string &s)
Construct a new Exception.
Definition: cryptlib.h:183
virtual void IsolatedInitialize(const NameValuePairs &parameters)
Initialize or reinitialize this object, without signal propagation.
Definition: cryptlib.h:1721
Exception thrown when the object is in the wrong state for the operation.
Definition: cryptlib.h:1294
const CryptoMaterial & GetMaterial() const
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2498
Interface for public-key signers.
Definition: cryptlib.h:2727
Interface for public-key encryptors.
Definition: cryptlib.h:2548
virtual bool CanModifyInput() const
Determines whether input can be modified by the callee.
Definition: cryptlib.h:1631
Converts an enumeration to a type suitable for use as a template parameter.
Definition: cryptlib.h:135
bool GetThisObject(T &object) const
Get a copy of this object or subobject.
Definition: cryptlib.h:328
bool CanUseRandomIVs() const
Determines if the object can use random IVs.
Definition: cryptlib.h:716
CipherDir
Specifies a direction for a cipher to operate.
Definition: cryptlib.h:123
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const
Decrypt a fixed size ciphertext.
Definition: cryptlib.h:2628
Flush(true) was called but it can&#39;t completely flush its buffers.
Definition: cryptlib.h:230
Thrown when an unexpected type is encountered.
Definition: cryptlib.h:300
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2474
Interface for asymmetric algorithms using private keys.
Definition: cryptlib.h:2467
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:1235
BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
Definition: cryptlib.cpp:40
virtual bool IsProbabilistic() const =0
Determines whether a signature scheme requires a random number generator.
ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
Construct a ValueTypeMismatch.
Definition: cryptlib.h:307
virtual bool AllowNonrecoverablePart() const =0
Determines whether the non-recoverable message part can be signed.
word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
Get a named value with type word64, with default.
Definition: cryptlib.h:413
virtual unsigned int NumberOfMessagesInThisSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:1986
virtual Clonable * Clone() const
Copies this object.
Definition: cryptlib.h:566
CipherDir GetCipherDirection() const
Provides the direction of the cipher.
Definition: cryptlib.h:912
EnumToType< ByteOrder, LITTLE_ENDIAN_ORDER > LittleEndian
Provides a constant for LittleEndian.
Definition: cryptlib.h:150
Library configuration file.
Interface for random number generators.
Definition: cryptlib.h:1349
Common C++ header files.
void ProcessString(byte *inoutString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1032
size_t messageLength
Recovered message length if isValidCoding is true, undefined otherwise.
Definition: cryptlib.h:278
virtual const PublicKey & GetPublicKey() const
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2462
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1784
virtual size_t SignatureLength() const =0
Provides the signature length if it only depends on the key.
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this hash.
Definition: cryptlib.h:1142
Interface for buffered transformations.
Definition: cryptlib.h:1564
Interface for private keys.
Definition: cryptlib.h:2396
virtual const BufferedTransformation * AttachedTransformation() const
Returns the object immediately attached to this object.
Definition: cryptlib.h:2215
Interface for cloning objects.
Definition: cryptlib.h:556
virtual size_t FixedCiphertextLength() const
Provides the fixed ciphertext length, if one exists.
Definition: cryptlib.h:2537
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:1905
bool operator==(const OID &lhs, const OID &rhs)
Compare two OIDs for equality.
Data integerity check, such as CRC or MAC, failed.
Definition: cryptlib.h:171
byte order is little-endian
Definition: cryptlib.h:145
Interface for one direction (encryption or decryption) of a block cipher.
Definition: cryptlib.h:1248
virtual std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition: cryptlib.h:608
void SetWhat(const std::string &s)
Sets the error string for the exception.
Definition: cryptlib.h:190
Interface for objects that can be waited on.
Definition: cryptlib.h:1515
the cipher is performing encryption
Definition: cryptlib.h:125
size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
Input multiple bytes that may be modified by callee.
Definition: cryptlib.h:1640
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition: cryptlib.h:2348
const std::type_info & GetRetrievingTypeInfo() const
Provides the retrieveing type.
Definition: cryptlib.h:317
virtual size_t MaxRecoverableLength() const =0
Provides the length of longest message that can be recovered.
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition: cryptlib.h:2353
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:2082
virtual bool IsLastBlockSpecial() const
Determines if the last block receives special processing.
Definition: cryptlib.h:1026
bool MessageEnd(int propagation=-1, bool blocking=true)
Signals the end of messages to the object.
Definition: cryptlib.h:1648
Interface for domains of simple key agreement protocols.
Definition: cryptlib.h:2863
virtual unsigned int GetMaxWaitObjectCount() const =0
Maximum number of wait objects that this object can return.
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2477
bool CanUsePredictableIVs() const
Determines if the object can use random but possibly predictable IVs.
Definition: cryptlib.h:721
Exception thrown when a filter does not support named channels.
Definition: cryptlib.h:2060
Returns a decoding results.
Definition: cryptlib.h:255
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition: cryptlib.h:2341
Exception thrown when trying to encrypt plaintext of invalid length.
Definition: cryptlib.h:2552
Input data was received that did not conform to expected format.
Definition: cryptlib.h:173
lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
move transferMax bytes of the buffered output to target as input
Definition: cryptlib.h:1867
Interface for public-key decryptors.
Definition: cryptlib.h:2583
virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const &callStack)=0
Retrieves waitable objects.
A method was called which was not implemented.
Definition: cryptlib.h:223
Exception throw when the private or public key is too short to sign or verify.
Definition: cryptlib.h:2650
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1586
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.h:482
virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0
Check this object for errors.
bool operator!=(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition: cryptlib.h:273
virtual void Restart()
Restart the hash.
Definition: cryptlib.h:1119
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition: cryptlib.h:748
unsigned int DigestSize() const
Definition: cryptlib.h:2715
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:644
Interface for encoding and decoding ASN1 objects.
Definition: cryptlib.h:3134
StreamTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:925
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition: cryptlib.h:755
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:937
void ProcessString(byte *outString, const byte *inString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1040
virtual unsigned int GetOptimalBlockSizeUsed() const
Provides the number of bytes used in the current block when processing at optimal block size...
Definition: cryptlib.h:948
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:2092
DecodingResult()
Constructs a DecodingResult.
Definition: cryptlib.h:259
BufferedTransformation()
Construct a BufferedTransformation.
Definition: cryptlib.h:1570
Exception thrown when a filter does not recognize a named channel.
Definition: cryptlib.h:2063
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode...
Definition: cryptlib.h:1256
Multiple precision integer with arithmetic operations.
Definition: integer.h:49
DecodingResult(size_t len)
Constructs a DecodingResult.
Definition: cryptlib.h:263
void ProcessBlock(const byte *inBlock, byte *outBlock) const
Encrypt or decrypt a block.
Definition: cryptlib.h:851
Exception throw when the private or public key has a length that can&#39;t be used.
Definition: cryptlib.h:2641
Interface for algorithms that take byte strings as keys.
Definition: cryptlib.h:613
bool operator==(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition: cryptlib.h:268
virtual unsigned int NumberOfMessageSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:1989
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2209
HashTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:1092
virtual void SetAutoSignalPropagation(int propagation)
Set propagation of automatically generated and transferred signals.
Definition: cryptlib.h:1778
Interface for asymmetric algorithms using public keys.
Definition: cryptlib.h:2441
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:733
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...
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:500
virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0
Get a named value.
Namespace containing testing and benchmark classes.
Definition: cryptlib.h:547
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
Definition: cryptlib.h:1370
bool CanUseStructuredIVs() const
Determines if the object can use structured IVs.
Definition: cryptlib.h:727
Interface for public-key signers and verifiers.
Definition: cryptlib.h:2635
Interface for the data processing portion of stream ciphers.
Definition: cryptlib.h:917
virtual void Detach(BufferedTransformation *newAttachment=NULL)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:2224
const std::string & GetOperation() const
Retrieve the operating system API that reported the error.
Definition: cryptlib.h:245
byte order is big-endian
Definition: cryptlib.h:147
virtual bool Verify(const byte *digest)
Verifies the hash of the current message.
Definition: cryptlib.h:1170
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:591
RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:400
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:60
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:1206
int GetErrorCode() const
Retrieve the error code returned by the operating system.
Definition: cryptlib.h:247
const char * BlockSize()
int, in bytes
Definition: argnames.h:27
virtual bool IsolatedMessageSeriesEnd(bool blocking)
Marks the end of a series of messages, without signal propagation.
Definition: cryptlib.h:1735
const unsigned long INFINITE_TIME
Represents infinite time.
Definition: cryptlib.h:130
ErrorType GetErrorType() const
Retrieves the error type for the exception.
Definition: cryptlib.h:192
void GetRequiredParameter(const char *className, const char *name, T &value) const
Retrieves a required name/value pair.
Definition: cryptlib.h:439
Interface for all crypto algorithms.
Definition: cryptlib.h:570
size_t Put(const byte *inString, size_t length, bool blocking=true)
Input a byte buffer for processing.
Definition: cryptlib.h:1596
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2711
unsigned int DefaultIVLength() const
Provides the default size of an IV.
Definition: cryptlib.h:738
A decryption filter encountered invalid ciphertext.
Definition: cryptlib.h:216
Interface for key agreement algorithms.
Definition: cryptlib.h:2488
Exception thrown by objects that have not implemented nonblocking input processing.
Definition: cryptlib.h:1688
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:1158
static 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:425
virtual void Seek(lword pos)
Seek to an absolute position.
Definition: cryptlib.h:1058
void ProcessBlock(byte *inoutBlock) const
Encrypt or decrypt a block in place.
Definition: cryptlib.h:860
IV_Requirement
Secure IVs requirements as enumerated values.
Definition: cryptlib.h:691
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2450
void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
Transfer all bytes from this object to another BufferedTransformation.
Definition: cryptlib.h:1971
virtual const CryptoParameters & GetCryptoParameters() const
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2505
Interface for public-key signature verifiers.
Definition: cryptlib.h:2791
virtual bool IsPermutation() const
Determines if the transformation is a permutation.
Definition: cryptlib.h:874
virtual byte * CreateUpdateSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1107
void Shuffle(IT begin, IT end)
Randomly shuffle the specified array.
Definition: cryptlib.h:1425
lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
copy copyMax bytes of the buffered output to target as input
Definition: cryptlib.h:1892
Debugging and diagnostic assertions.
bool GetWord64Value(const char *name, word64 &value) const
Get a named value with type word64.
Definition: cryptlib.h:404
Interface for hash functions and data processing part of MACs.
Definition: cryptlib.h:1084
Interface for crypto material, such as public and private keys, and crypto parameters.
Definition: cryptlib.h:2249
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1625
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2376
Interface for password based key derivation functions.
Definition: cryptlib.h:1499
CryptoMaterial & AccessMaterial()
Retrieves a reference to Crypto Parameters.
Definition: cryptlib.h:2495
An invalid argument was detected.
Definition: cryptlib.h:167
Interface for generatable crypto material, such as private keys and crypto parameters.
Definition: cryptlib.h:2365
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:1662
virtual bool RecoverablePartFirst() const =0
Determines whether the recoverable part must be input before the non-recoverable part.
Interface for crypto prameters.
Definition: cryptlib.h:2401
bool GetThisPointer(T *&ptr) const
Get a pointer to this object.
Definition: cryptlib.h:337
bool isValidCoding
Flag to indicate the decoding is valid.
Definition: cryptlib.h:276
BufferedTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:1575
Namespace containing value name definitions.
Definition: argnames.h:13
BufferedTransformation received a Flush(true) signal but can&#39;t flush buffers.
Definition: cryptlib.h:169
void SetErrorType(ErrorType errorType)
Sets the error type for the exceptions.
Definition: cryptlib.h:194
int LibraryVersion(...)
Specifies the build-time version of the library.
Definition: cryptlib.cpp:984
Interface for public keys.
Definition: cryptlib.h:2391
Crypto++ library namespace.
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:350
Interface for the data processing part of block ciphers.
Definition: cryptlib.h:827
FlagsForAdvancedProcessBlocks
Bit flags that control AdvancedProcessBlocks() behavior.
Definition: cryptlib.h:887
The IV must be random and unpredictable.
Definition: cryptlib.h:697
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition: cryptlib.h:712
Interface for domains of authenticated key agreement protocols.
Definition: cryptlib.h:2922
virtual bool GetNextMessageSeries()
Retrieve the next message in a series.
Definition: cryptlib.h:1983
void TruncatedFinal(byte *digest, size_t digestSize)
Definition: cryptlib.h:2719
A method was called which was not implemented.
Definition: cryptlib.h:165
unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
Transfer messages from this object to another BufferedTransformation.
Definition: cryptlib.h:1949
byte ProcessByte(byte input)
Encrypt or decrypt a byte.
Definition: cryptlib.h:1046
bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition: cryptlib.h:386
const std::string AAD_CHANNEL
Channel for additional authenticated data.
Definition: cryptlib.h:491
virtual void BEREncode(BufferedTransformation &bt) const
Encode this object into a BufferedTransformation.
Definition: cryptlib.h:3153
Error reading from input device or writing to output device.
Definition: cryptlib.h:175
virtual void Save(BufferedTransformation &bt) const
Saves a key to a BufferedTransformation.
Definition: cryptlib.h:2299
virtual bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: cryptlib.h:2322
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:2133
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:1683
virtual void Final(byte *digest)
Computes the hash of the current message.
Definition: cryptlib.h:1114
Input data was received that did not conform to expected format.
Definition: cryptlib.h:209
virtual lword MaxFooterLength() const
Provides the the maximum length of AAD.
Definition: cryptlib.h:1309
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this cipher.
Definition: cryptlib.h:944
virtual const PrivateKey & GetPrivateKey() const
Retrieves a reference to a Private Key.
Definition: cryptlib.h:2484
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Public Key.
Definition: cryptlib.h:2454
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:2668
EnumToType< ByteOrder, BIG_ENDIAN_ORDER > BigEndian
Provides a constant for BigEndian.
Definition: cryptlib.h:152
virtual bool Attachable()
Determines whether the object allows attachment.
Definition: cryptlib.h:2203
void GetRequiredIntParameter(const char *className, const char *name, int &value) const
Retrieves a required name/value pair.
Definition: cryptlib.h:454
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:1186
Namespace containing weak and wounded algorithms.
Definition: arc4.cpp:14
virtual bool SignatureUpfront() const
Determines whether the signature must be input before the message.
Definition: cryptlib.h:2699
std::string GetValueNames() const
Get a list of value names that can be retrieved.
Definition: cryptlib.h:375
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: cryptlib.h:1362
Interface for key derivation functions.
Definition: cryptlib.h:1435
virtual size_t FixedMaxPlaintextLength() const
Provides the maximum plaintext length given a fixed ciphertext length.
Definition: cryptlib.h:2544
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition: cryptlib.h:2121
virtual unsigned int MinLastBlockSize() const
Provides the size of the last block.
Definition: cryptlib.h:993
Interface for retrieving values given their names.
Definition: cryptlib.h:293
Exception thrown when an ASN.1 BER decoing error is encountered.
Definition: cryptlib.h:3123
The IV must be random and possibly predictable.
Definition: cryptlib.h:695
virtual unsigned int OptimalNumberOfParallelBlocks() const
Determines the number of blocks that can be processed in parallel.
Definition: cryptlib.h:884
const std::string & GetWhat() const
Retrieves a string describing the exception.
Definition: cryptlib.h:188