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