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