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