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