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