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