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