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