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