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