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