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