Crypto++  5.6.3
Free C++ class library of cryptographic schemes
cryptlib.h
Go to the documentation of this file.
1 // cryptlib.h - written and placed in the public domain by Wei Dai
2 
3 //! \file cryptlib.h
4 //! \brief Abstract base classes that provide a uniform interface to this library.
5 
6 /*! \mainpage Crypto++ Library 5.6.3 API Reference
7 <dl>
8 <dt>Abstract Base Classes<dd>
9  cryptlib.h
10 <dt>Authenticated Encryption Modes<dd>
11  CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)"
12 <dt>Block Ciphers<dd>
13  \ref Rijndael "AES", Weak::ARC4, Blowfish, BTEA, Camellia, CAST128, CAST256, DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES",
14  \ref DES_XEX3 "DESX", GOST, IDEA, \ref LR "Luby-Rackoff", MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent,
15  \ref SHACAL2 "SHACAL-2", SHARK, SKIPJACK,
16 Square, TEA, \ref ThreeWay "3-Way", Twofish, XTEA
17 <dt>Stream Ciphers<dd>
18  \ref Panama "Panama-LE", \ref Panama "Panama-BE", Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20
19 <dt>Hash Functions<dd>
20  SHA1, SHA224, SHA256, SHA384, SHA512, \ref SHA3 "SHA-3", Tiger, Whirlpool, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, Weak::MD2, Weak::MD4, Weak::MD5
21 <dt>Non-Cryptographic Checksums<dd>
22  CRC32, Adler32
23 <dt>Message Authentication Codes<dd>
24  VMAC, HMAC, CBC_MAC, CMAC, DMAC, TTMAC, \ref GCM "GCM (GMAC)"
25 <dt>Random Number Generators<dd>
26  NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG,
27  \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)", RDRAND, RDSEED
28 <dt>Key Derivation and Password-based Cryptography<dd>
29  HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)", \ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)"
30 <dt>Public Key Cryptosystems<dd>
31  DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
32 <dt>Public Key Signature Schemes<dd>
33  DSA2, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, RabinSS, RWSS, ESIGN
34 <dt>Key Agreement<dd>
35  DH, DH2, MQV, ECDH, ECMQV, XTR_DH
36 <dt>Algebraic Structures<dd>
37  Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
38  ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP
39 <dt>Secret Sharing and Information Dispersal<dd>
40  SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
41 <dt>Compression<dd>
42  Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
43 <dt>Input Source Classes<dd>
44  StringSource, ArraySource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource
45 <dt>Output Sink Classes<dd>
46  StringSinkTemplate, StringSink, ArraySink, FileSink, SocketSink, WindowsPipeSink, RandomNumberSink
47 <dt>Filter Wrappers<dd>
48  StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter
49 <dt>Binary to Text Encoders and Decoders<dd>
50  HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder, Base32Decoder
51 <dt>Wrappers for OS features<dd>
52  Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer
53 <dt>FIPS 140 validated cryptography<dd>
54  fips140.h
55 </dl>
56 
57 In the DLL version of Crypto++, only the following implementation class are available.
58 <dl>
59 <dt>Block Ciphers<dd>
60  AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK
61 <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
62  \ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>", \ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>"
63 <dt>Hash Functions<dd>
64  SHA1, SHA224, SHA256, SHA384, SHA512
65 <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
66  RSASS<PKCS1v15, H>, RSASS<PSS, H>, RSASS_ISO<H>, RWSS<P1363_EMSA2, H>, DSA, ECDSA<ECP, H>, ECDSA<EC2N, H>
67 <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
68  HMAC<H>, CBC_MAC<DES_EDE2>, CBC_MAC<DES_EDE3>, GCM<AES>
69 <dt>Random Number Generators<dd>
70  DefaultAutoSeededRNG (AutoSeededX917RNG<AES>)
71 <dt>Key Agreement<dd>
72  DH, DH2
73 <dt>Public Key Cryptosystems<dd>
74  RSAES<OAEP<SHA1> >
75 </dl>
76 
77 <p>This reference manual is a work in progress. Some classes are lack detailed descriptions.
78 <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
79 <p>Thanks to Ryan Phillips for providing the Doxygen configuration file
80 and getting us started on the manual.
81 */
82 
83 #ifndef CRYPTOPP_CRYPTLIB_H
84 #define CRYPTOPP_CRYPTLIB_H
85 
86 #include "config.h"
87 #include "stdcpp.h"
88 
89 #if CRYPTOPP_MSC_VERSION
90 # pragma warning(push)
91 # pragma warning(disable: 4127 4189 4702)
92 #endif
93 
94 NAMESPACE_BEGIN(CryptoPP)
95 
96 // forward declarations
97 class Integer;
100 
101 //! \brief Specifies a direction for a cipher to operate
102 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 
1180 //! \brief Random Number Generator that does not produce random numbers
1181 //! \returns reference that can be passed to functions that require a RandomNumberGenerator
1182 //! \details NullRNG() returns a reference that can be passed to functions that require a
1183 //! RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented
1184 //! when a generation function is called.
1185 //! \sa ClassNullRNG
1186 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
1187 
1188 //! \class WaitObjectContainer
1189 class WaitObjectContainer;
1190 //! \class CallStack
1191 class CallStack;
1192 
1193 //! \brief Interface for objects that can be waited on.
1194 class CRYPTOPP_NO_VTABLE Waitable
1195 {
1196 public:
1197  virtual ~Waitable() {}
1198 
1199  //! \brief Maximum number of wait objects that this object can return
1200  virtual unsigned int GetMaxWaitObjectCount() const =0;
1201 
1202  //! \brief Retrieves waitable objects
1203  //! \param container the wait container to receive the references to the objects.
1204  //! \param callStack CallStack object used to select waitable objects
1205  //! \details GetWaitObjects is usually called in one of two ways. First, it can
1206  //! be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1207  //! Second, if in an outer GetWaitObjects() method that itself takes a callStack
1208  //! parameter, it can be called like
1209  //! <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1210  virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
1211 
1212  //! wait on this object
1213  /*! same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container */
1214  bool Wait(unsigned long milliseconds, CallStack const& callStack);
1215 };
1216 
1217 //! \brief Default channel for BufferedTransformation
1218 //! \details DEFAULT_CHANNEL is equal to an empty string
1219 extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
1220 
1221 //! \brief Channel for additional authenticated data
1222 //! \details AAD_CHANNEL is equal to "AAD"
1223 extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
1224 
1225 //! \brief Interface for buffered transformations
1226 //! \details BufferedTransformation is a generalization of BlockTransformation,
1227 //! StreamTransformation and HashTransformation.
1228 //! \details A buffered transformation is an object that takes a stream of bytes as input (this may
1229 //! be done in stages), does some computation on them, and then places the result into an internal
1230 //! buffer for later retrieval. Any partial result already in the output buffer is not modified
1231 //! by further input.
1232 //! \details If a method takes a "blocking" parameter, and you pass false for it, then the method
1233 //! will return before all input has been processed if the input cannot be processed without waiting
1234 //! (for network buffers to become available, for example). In this case the method will return true
1235 //! or a non-zero integer value. When this happens you must continue to call the method with the same
1236 //! parameters until it returns false or zero, before calling any other method on it or attached
1237 //! /p BufferedTransformation. The integer return value in this case is approximately
1238 //! the number of bytes left to be processed, and can be used to implement a progress bar.
1239 //! \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on
1240 //! the signal to attached BufferedTransformation objects, with propagation decremented at each
1241 //! step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation.
1242 //! \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual
1243 //! number of bytes retrieved, which is the lesser of the request number and MaxRetrievable().
1244 //! \details \a Most of the input functions, like Put() and PutWord32(), return the number of
1245 //! bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value
1246 //! means bytes remain to be processed.
1247 //! \nosubgrouping
1248 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
1249 {
1250 public:
1251  // placed up here for CW8
1252  static const std::string &NULL_CHANNEL; // same as DEFAULT_CHANNEL, for backwards compatibility
1253 
1254  BufferedTransformation() : Algorithm(false) {}
1255 
1256  //! \brief Provides a reference to this object
1257  //! \returns A reference to this object
1258  //! \details Useful for passing a temporary object to a function that takes a non-const reference
1259  BufferedTransformation& Ref() {return *this;}
1260 
1261  //! \name INPUT
1262  //@{
1263 
1264  //! \brief Input a byte for processing
1265  //! \param inByte the 8-bit byte (octet) to be processed.
1266  //! \param blocking specifies whether the object should block when processing input.
1267  //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
1268  //! \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>.
1269  size_t Put(byte inByte, bool blocking=true)
1270  {return Put(&inByte, 1, blocking);}
1271 
1272  //! \brief Input a byte buffer for processing
1273  //! \param inString the byte buffer to process
1274  //! \param length the size of the string, in bytes
1275  //! \param blocking specifies whether the object should block when processing input
1276  //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
1277  //! \details Internally, Put() calls Put2().
1278  size_t Put(const byte *inString, size_t length, bool blocking=true)
1279  {return Put2(inString, length, 0, blocking);}
1280 
1281  //! Input a 16-bit word for processing.
1282  //! \param value the 16-bit value to be processed
1283  //! \param order the ByteOrder in which the word should be processed
1284  //! \param blocking specifies whether the object should block when processing input
1285  //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
1286  size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1287 
1288  //! Input a 32-bit word for processing.
1289  //! \param value the 32-bit value to be processed.
1290  //! \param order the ByteOrder in which the word should be processed.
1291  //! \param blocking specifies whether the object should block when processing input.
1292  //! \returns the number of bytes that remain in the block (i.e., bytes not processed)
1293  size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1294 
1295  //! \brief Request space which can be written into by the caller
1296  //! \param size the requested size of the buffer
1297  //! \details The purpose of this method is to help avoid extra memory allocations.
1298  //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1299  //! size is the requested size of the buffer. When the call returns, size is the size of
1300  //! the array returned to the caller.
1301  //! \details The base class implementation sets size to 0 and returns NULL.
1302  //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
1303  //! an ArraySink, the pointer to the array is returned and the size is remaining size.
1304  virtual byte * CreatePutSpace(size_t &size)
1305  {size=0; return NULL;}
1306 
1307  //! \brief Determines whether input can be modifed by the callee
1308  //! \returns true if input can be modified, false otherwise
1309  //! \details The base class implementation returns false.
1310  virtual bool CanModifyInput() const
1311  {return false;}
1312 
1313  //! \brief Input multiple bytes that may be modified by callee.
1314  //! \param inString the byte buffer to process
1315  //! \param length the size of the string, in bytes
1316  //! \param blocking specifies whether the object should block when processing input
1317  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1318  //! number of bytes that were \a not processed
1319  size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
1320  {return PutModifiable2(inString, length, 0, blocking);}
1321 
1322  //! \brief Signals the end of messages to the object
1323  //! \param propagation the number of attached transformations the MessageEnd() signal should be passed
1324  //! \param blocking specifies whether the object should block when processing input
1325  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1326  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1327  bool MessageEnd(int propagation=-1, bool blocking=true)
1328  {return !!Put2(NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
1329 
1330  //! \brief Input multiple bytes for processing and signal the end of a message
1331  //! \param inString the byte buffer to process
1332  //! \param length the size of the string, in bytes
1333  //! \param propagation the number of attached transformations the MessageEnd() signal should be passed
1334  //! \param blocking specifies whether the object should block when processing input
1335  //! \details Internally, PutMessageEnd() calls Put2() with a modified propagation to
1336  //! ensure all attached transformations finish processing the message.
1337  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1338  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1339  size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
1340  {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
1341 
1342  //! \brief Input multiple bytes for processing
1343  //! \param inString the byte buffer to process
1344  //! \param length the size of the string, in bytes
1345  //! \param messageEnd means how many filters to signal MessageEnd() to, including this one
1346  //! \param blocking specifies whether the object should block when processing input
1347  //! \details Derived classes must implement Put2().
1348  virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
1349 
1350  //! \brief Input multiple bytes that may be modified by callee.
1351  //! \param inString the byte buffer to process.
1352  //! \param length the size of the string, in bytes.
1353  //! \param messageEnd means how many filters to signal MessageEnd() to, including this one.
1354  //! \param blocking specifies whether the object should block when processing input.
1355  //! \details Internally, PutModifiable2() calls Put2().
1356  virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
1357  {return Put2(inString, length, messageEnd, blocking);}
1358 
1359  //! \brief thrown by objects that have not implemented nonblocking input processing
1361  {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
1362  //@}
1363 
1364  //! \name WAITING
1365  //@{
1366  //! \brief Retrieves the maximum number of waitable objects
1367  unsigned int GetMaxWaitObjectCount() const;
1368 
1369  //! \brief Retrieves waitable objects
1370  //! \param container the wait container to receive the references to the objects
1371  //! \param callStack CallStack object used to select waitable objects
1372  //! \details GetWaitObjects is usually called in one of two ways. First, it can
1373  //! be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
1374  //! Second, if in an outer GetWaitObjects() method that itself takes a callStack
1375  //! parameter, it can be called like
1376  //! <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
1377  void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
1378  //@} // WAITING
1379 
1380  //! \name SIGNALS
1381  //@{
1382 
1383  //! \brief Initialize or reinitialize this object, without signal propagation
1384  //! \param parameters a set of NameValuePairs used to initialize this object
1385  //! \throws NotImplemented
1386  //! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
1387  //! number of arbitrarily typed arguments. The function avoids the need for multiple constuctors providing
1388  //! all possible combintations of configurable parameters.
1389  //! \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization
1390  //! should be propagated, then use the Initialize() function.
1391  //! \details Setting propagation to <tt>-1</tt> means unlimited propagation.
1392  //! \details If a derived class does not override IsolatedInitialize(), then the base class throws
1393  //! NotImplemented.
1394  virtual void IsolatedInitialize(const NameValuePairs &parameters) {
1395  CRYPTOPP_UNUSED(parameters);
1396  throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
1397  }
1398 
1399  //! \brief Flushes data buffered by this object, without signal propagation
1400  //! \param hardFlush indicates whether all data should be flushed
1401  //! \param blocking specifies whether the object should block when processing input
1402  //! \note hardFlush must be used with care
1403  virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
1404 
1405  //! \brief Marks the end of a series of messages, without signal propagation
1406  //! \param blocking specifies whether the object should block when completing the processing on
1407  //! the current series of messages
1408  virtual bool IsolatedMessageSeriesEnd(bool blocking)
1409  {CRYPTOPP_UNUSED(blocking); return false;}
1410 
1411  //! \brief Initialize or reinitialize this object, with signal propagation
1412  //! \param parameters a set of NameValuePairs used to initialize or reinitialize this object
1413  //! and attached transformations
1414  //! \param propagation the number of attached transformations the Initialize() signal should be passed
1415  //! \details Initialize() is used to initialize or reinitialize an object using a variable number of
1416  //! arbitrarily typed arguments. The function avoids the need for multiple constuctors providing
1417  //! all possible combintations of configurable parameters.
1418  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1419  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1420  virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
1421 
1422  //! \brief Flush buffered input and/or output, with signal propagation
1423  //! \param hardFlush is used to indicate whether all data should be flushed
1424  //! \param propagation the number of attached transformations the Flush() signal should be passed
1425  //! \param blocking specifies whether the object should block when processing input
1426  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1427  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1428  //! \note Hard flushes must be used with care. It means try to process and output everything, even if
1429  //! there may not be enough data to complete the action. For example, hard flushing a HexDecoder
1430  //! would cause an error if you do it after inputing an odd number of hex encoded characters.
1431  //! \note For some types of filters, like ZlibDecompressor, hard flushes can only
1432  //! be done at "synchronization points". These synchronization points are positions in the data
1433  //! stream that are created by hard flushes on the corresponding reverse filters, in this
1434  //! example ZlibCompressor. This is useful when zlib compressed data is moved across a
1435  //! network in packets and compression state is preserved across packets, as in the SSH2 protocol.
1436  virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
1437 
1438  //! \brief Marks the end of a series of messages, with signal propagation
1439  //! \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
1440  //! \param blocking specifies whether the object should block when processing input
1441  //! \details Each object that receives the signal will perform its processing, decrement
1442  //! propagation, and then pass the signal on to attached transformations if the value is not 0.
1443  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1444  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1445  //! \note There should be a MessageEnd() immediately before MessageSeriesEnd().
1446  virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
1447 
1448  //! \brief Set propagation of automatically generated and transferred signals
1449  //! \param propagation then new value
1450  //! \details Setting propagation to <tt>0</tt> means do not automaticly generate signals. Setting
1451  //! propagation to <tt>-1</tt> means unlimited propagation.
1452  virtual void SetAutoSignalPropagation(int propagation)
1453  {CRYPTOPP_UNUSED(propagation);}
1454 
1455  //! \brief Retrieve automatic signal propagation value
1456  virtual int GetAutoSignalPropagation() const {return 0;}
1457 public:
1458 
1459 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
1460  void Close() {MessageEnd();}
1461 #endif
1462  //@}
1463 
1464  //! \name RETRIEVAL OF ONE MESSAGE
1465  //@{
1466 
1467  //! \brief Provides the number of bytes ready for retrieval
1468  //! \returns the number of bytes ready for retrieval
1469  //! \details All retrieval functions return the actual number of bytes retrieved, which is
1470  //! the lesser of the request number and MaxRetrievable()
1471  virtual lword MaxRetrievable() const;
1472 
1473  //! \brief Determines whether bytes are ready for retrieval
1474  //! \returns true if bytes are available for retrieval, false otherwise
1475  virtual bool AnyRetrievable() const;
1476 
1477  //! \brief Retrieve a 8-bit byte
1478  //! \param outByte the 8-bit value to be retrieved
1479  //! \returns the number of bytes consumed during the call.
1480  //! \details Use the return value of Get to detect short reads.
1481  virtual size_t Get(byte &outByte);
1482 
1483  //! \brief Retrieve a block of bytes
1484  //! \param outString a block of bytes
1485  //! \param getMax the number of bytes to Get
1486  //! \returns the number of bytes consumed during the call.
1487  //! \details Use the return value of Get to detect short reads.
1488  virtual size_t Get(byte *outString, size_t getMax);
1489 
1490  //! \brief Peek a 8-bit byte
1491  //! \param outByte the 8-bit value to be retrieved
1492  //! \returns the number of bytes read during the call.
1493  //! \details Peek does not remove bytes from the object. Use the return value of
1494  //! Get to detect short reads.
1495  virtual size_t Peek(byte &outByte) const;
1496 
1497  //! \brief Peek a block of bytes
1498  //! \param outString a block of bytes
1499  //! \param peekMax the number of bytes to Peek
1500  //! \returns the number of bytes read during the call.
1501  //! \details Peek does not remove bytes from the object. Use the return value of
1502  //! Get to detect short reads.
1503  virtual size_t Peek(byte *outString, size_t peekMax) const;
1504 
1505  //! \brief Retrieve a 16-bit word
1506  //! \param value the 16-bit value to be retrieved
1507  //! \param order the ByteOrder in which the word should be retrieved
1508  //! \returns the number of bytes consumed during the call.
1509  //! \details Use the return value of GetWord16 to detect short reads.
1510  size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1511 
1512  //! \brief Retrieve a 32-bit word
1513  //! \param value the 32-bit value to be retrieved
1514  //! \param order the ByteOrder in which the word should be retrieved
1515  //! \returns the number of bytes consumed during the call.
1516  //! \details Use the return value of GetWord16 to detect short reads.
1517  size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1518 
1519  //! \brief Peek a 16-bit word
1520  //! \param value the 16-bit value to be retrieved
1521  //! \param order the ByteOrder in which the word should be retrieved
1522  //! \returns the number of bytes consumed during the call.
1523  //! \details Peek does not consume bytes in the stream. Use the return value
1524  //! of GetWord16 to detect short reads.
1525  size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1526 
1527  //! \brief Peek a 32-bit word
1528  //! \param value the 32-bit value to be retrieved
1529  //! \param order the ByteOrder in which the word should be retrieved
1530  //! \returns the number of bytes consumed during the call.
1531  //! \details Peek does not consume bytes in the stream. Use the return value
1532  //! of GetWord16 to detect short reads.
1533  size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1534 
1535  //! move transferMax bytes of the buffered output to target as input
1536 
1537  //! \brief Transfer bytes from this object to another BufferedTransformation
1538  //! \param target the destination BufferedTransformation
1539  //! \param transferMax the number of bytes to transfer
1540  //! \param channel the channel on which the transfer should occur
1541  //! \returns the number of bytes transferred during the call.
1542  //! \details TransferTo removes bytes from this object and moves them to the destination.
1543  //! \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2.
1544  lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
1545  {TransferTo2(target, transferMax, channel); return transferMax;}
1546 
1547  //! \brief Discard skipMax bytes from the output buffer
1548  //! \param skipMax the number of bytes to discard
1549  //! \details Skip always returns skipMax.
1550  virtual lword Skip(lword skipMax=LWORD_MAX);
1551 
1552  //! copy copyMax bytes of the buffered output to target as input
1553 
1554  //! \brief Copy bytes from this object to another BufferedTransformation
1555  //! \param target the destination BufferedTransformation
1556  //! \param copyMax the number of bytes to copy
1557  //! \param channel the channel on which the transfer should occur
1558  //! \returns the number of bytes copied during the call.
1559  //! \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
1560  //! \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2.
1561  lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1562  {return CopyRangeTo(target, 0, copyMax, channel);}
1563 
1564  //! \brief Copy bytes from this object using an index to another BufferedTransformation
1565  //! \param target the destination BufferedTransformation
1566  //! \param position the 0-based index of the byte stream to begin the copying
1567  //! \param copyMax the number of bytes to copy
1568  //! \param channel the channel on which the transfer should occur
1569  //! \returns the number of bytes copied during the call.
1570  //! \details CopyTo copies bytes from this object to the destination. The bytes remain in this
1571  //! object. Copying begins at the index position in the current stream, and not from an absolute
1572  //! position in the stream.
1573  //! \details The function returns the new position in the stream after transferring the bytes starting at the index.
1574  lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
1575  {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
1576 
1577 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
1578  unsigned long MaxRetrieveable() const {return MaxRetrievable();}
1579 #endif
1580  //@}
1581 
1582  //! \name RETRIEVAL OF MULTIPLE MESSAGES
1583  //@{
1584 
1585  //! \brief Provides the number of bytes ready for retrieval
1586  //! \returns the number of bytes ready for retrieval
1587  virtual lword TotalBytesRetrievable() const;
1588 
1589  //! \brief Provides the number of meesages processed by this object
1590  //! \returns the number of meesages processed by this object
1591  //! \details NumberOfMessages returns number of times MessageEnd() has been
1592  //! received minus messages retrieved or skipped
1593  virtual unsigned int NumberOfMessages() const;
1594 
1595  //! \brief Determines if any messages are available for retrieval
1596  //! \returns true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
1597  //! \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
1598  virtual bool AnyMessages() const;
1599 
1600  //! \brief Start retrieving the next message
1601  //! \returns true if a message is ready for retrieval
1602  //! \details GetNextMessage() returns true if a message is ready for retrieval; false
1603  //! if no more messages exist or this message is not completely retrieved.
1604  virtual bool GetNextMessage();
1605 
1606  //! \brief Skip a number of meessages
1607  //! \returns 0 if the requested number of messages was skipped, non-0 otherwise
1608  //! \details SkipMessages() skips count number of messages. If there is an AttachedTransformation()
1609  //! then SkipMessages() is called on the attached transformation. If there is no attached
1610  //! transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo().
1611  virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
1612 
1613  //! \brief Transfer messages from this object to another BufferedTransformation
1614  //! \param target the destination BufferedTransformation
1615  //! \param count the number of messages to transfer
1616  //! \param channel the channel on which the transfer should occur
1617  //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
1618  //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination.
1619  //! If all bytes are not transferred for a message, then processing stops and the number of remaining
1620  //! bytes is returned. TransferMessagesTo() does not proceed to the next message.
1621  //! \details A return value of 0 indicates all messages were successfully transferred.
1622  unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
1623  {TransferMessagesTo2(target, count, channel); return count;}
1624 
1625  //! \brief Copies messages from this object to another BufferedTransformation
1626  //! \param target the destination BufferedTransformation
1627  //! \param count the number of messages to transfer
1628  //! \param channel the channel on which the transfer should occur
1629  //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
1630  //! \details CopyMessagesTo copies messages from this object and copies them to the destination.
1631  //! If all bytes are not transferred for a message, then processing stops and the number of remaining
1632  //! bytes is returned. CopyMessagesTo() does not proceed to the next message.
1633  //! \details A return value of 0 indicates all messages were successfully copied.
1634  unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
1635 
1636  //!
1637  virtual void SkipAll();
1638  //!
1639  void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
1640  {TransferAllTo2(target, channel);}
1641  //!
1642  void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
1643 
1644  virtual bool GetNextMessageSeries() {return false;}
1645  virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
1646  virtual unsigned int NumberOfMessageSeries() const {return 0;}
1647  //@}
1648 
1649  //! \name NON-BLOCKING TRANSFER OF OUTPUT
1650  //@{
1651 
1652  // upon return, byteCount contains number of bytes that have finished being transfered,
1653  // and returns the number of bytes left in the current transfer block
1654 
1655  //! \brief Transfer bytes from this object to another BufferedTransformation
1656  //! \param target the destination BufferedTransformation
1657  //! \param byteCount the number of bytes to transfer
1658  //! \param channel the channel on which the transfer should occur
1659  //! \param blocking specifies whether the object should block when processing input
1660  //! \returns the number of bytes that remain in the transfer block (i.e., bytes not transferred)
1661  //! \details TransferTo removes bytes from this object and moves them to the destination.
1662  //! Transfer begins at the index position in the current stream, and not from an absolute
1663  //! position in the stream.
1664  //! \details byteCount is an \a IN and \a OUT parameter. When the call is made,
1665  //! byteCount is the requested size of the transfer. When the call returns, byteCount is
1666  //! the number of bytes that were transferred.
1667  virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
1668 
1669  // upon return, begin contains the start position of data yet to be finished copying,
1670  // and returns the number of bytes left in the current transfer block
1671 
1672  //! \brief Copy bytes from this object to another BufferedTransformation
1673  //! \param target the destination BufferedTransformation
1674  //! \param begin the 0-based index of the first byte to copy in the stream
1675  //! \param end the 0-based index of the last byte to copy in the stream
1676  //! \param channel the channel on which the transfer should occur
1677  //! \param blocking specifies whether the object should block when processing input
1678  //! \returns the number of bytes that remain in the copy block (i.e., bytes not copied)
1679  //! \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not
1680  //! removed from this object. Copying begins at the index position in the current stream, and
1681  //! not from an absolute position in the stream.
1682  //! \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the
1683  //! starting position of the copy. When the call returns, begin is the position of the first
1684  //! byte that was \a not copied (which may be different tahn end). begin can be used for
1685  //! subsequent calls to CopyRangeTo2.
1686  virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
1687 
1688  // upon return, messageCount contains number of messages that have finished being transfered,
1689  // and returns the number of bytes left in the current transfer block
1690 
1691  //! \brief Transfer messages from this object to another BufferedTransformation
1692  //! \param target the destination BufferedTransformation
1693  //! \param messageCount the number of messages to transfer
1694  //! \param channel the channel on which the transfer should occur
1695  //! \param blocking specifies whether the object should block when processing input
1696  //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
1697  //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination.
1698  size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
1699 
1700  // returns the number of bytes left in the current transfer block
1701 
1702  //! \brief Transfer all bytes from this object to another BufferedTransformation
1703  //! \param target the destination BufferedTransformation
1704  //! \param channel the channel on which the transfer should occur
1705  //! \param blocking specifies whether the object should block when processing input
1706  //! \returns the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
1707  //! \details TransferMessagesTo2 removes messages from this object and moves them to the destination.
1708  size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
1709  //@}
1710 
1711  //! \name CHANNELS
1712  //@{
1713  //! \brief Exception thrown when a filter does not support named channels
1715  {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
1716  //! \brief Exception thrown when a filter does not recognize a named channel
1718  {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
1719 
1720  //! \brief Input a byte for processing on a channel
1721  //! \param channel the channel to process the data.
1722  //! \param inByte the 8-bit byte (octet) to be processed.
1723  //! \param blocking specifies whether the object should block when processing input.
1724  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1725  //! number of bytes that were \a not processed.
1726  size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
1727  {return ChannelPut(channel, &inByte, 1, blocking);}
1728 
1729  //! \brief Input a byte buffer for processing on a channel
1730  //! \param channel the channel to process the data
1731  //! \param inString the byte buffer to process
1732  //! \param length the size of the string, in bytes
1733  //! \param blocking specifies whether the object should block when processing input
1734  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1735  //! number of bytes that were \a not processed.
1736  size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
1737  {return ChannelPut2(channel, inString, length, 0, blocking);}
1738 
1739  //! \brief Input multiple bytes that may be modified by callee on a channel
1740  //! \param channel the channel to process the data.
1741  //! \param inString the byte buffer to process
1742  //! \param length the size of the string, in bytes
1743  //! \param blocking specifies whether the object should block when processing input
1744  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1745  //! number of bytes that were \a not processed.
1746  size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
1747  {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
1748 
1749  //! \brief Input a 16-bit word for processing on a channel.
1750  //! \param channel the channel to process the data.
1751  //! \param value the 16-bit value to be processed.
1752  //! \param order the ByteOrder in which the word should be processed.
1753  //! \param blocking specifies whether the object should block when processing input.
1754  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1755  //! number of bytes that were \a not processed.
1756  size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1757 
1758  //! \brief Input a 32-bit word for processing on a channel.
1759  //! \param channel the channel to process the data.
1760  //! \param value the 32-bit value to be processed.
1761  //! \param order the ByteOrder in which the word should be processed.
1762  //! \param blocking specifies whether the object should block when processing input.
1763  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1764  //! number of bytes that were \a not processed.
1765  size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1766 
1767  //! \brief Signal the end of a message
1768  //! \param channel the channel to process the data.
1769  //! \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed
1770  //! \param blocking specifies whether the object should block when processing input
1771  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1772  //! number of bytes that were \a not processed.
1773  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1774  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1775  bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
1776  {return !!ChannelPut2(channel, NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
1777 
1778  //! \brief Input multiple bytes for processing and signal the end of a message
1779  //! \param channel the channel to process the data.
1780  //! \param inString the byte buffer to process
1781  //! \param length the size of the string, in bytes
1782  //! \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed
1783  //! \param blocking specifies whether the object should block when processing input
1784  //! \returns 0 indicates all bytes were processed during the call. Non-0 indicates the
1785  //! number of bytes that were \a not processed.
1786  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1787  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1788  size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
1789  {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
1790 
1791  //! \brief Request space which can be written into by the caller
1792  //! \param channel the channel to process the data
1793  //! \param size the requested size of the buffer
1794  //! \details The purpose of this method is to help avoid extra memory allocations.
1795  //! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
1796  //! size is the requested size of the buffer. When the call returns, size is the size of
1797  //! the array returned to the caller.
1798  //! \details The base class implementation sets size to 0 and returns NULL.
1799  //! \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
1800  //! an ArraySink, the pointer to the array is returned and the size is remaining size.
1801  virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
1802 
1803  //! \brief Input multiple bytes for processing on a channel.
1804  //! \param channel the channel to process the data.
1805  //! \param inString the byte buffer to process.
1806  //! \param length the size of the string, in bytes.
1807  //! \param messageEnd means how many filters to signal MessageEnd() to, including this one.
1808  //! \param blocking specifies whether the object should block when processing input.
1809  virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
1810 
1811  //! \brief Input multiple bytes that may be modified by callee on a channel
1812  //! \param channel the channel to process the data
1813  //! \param inString the byte buffer to process
1814  //! \param length the size of the string, in bytes
1815  //! \param messageEnd means how many filters to signal MessageEnd() to, including this one
1816  //! \param blocking specifies whether the object should block when processing input
1817  virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
1818 
1819  //! \brief Flush buffered input and/or output on a channel
1820  //! \param channel the channel to flush the data
1821  //! \param hardFlush is used to indicate whether all data should be flushed
1822  //! \param propagation the number of attached transformations the ChannelFlush() signal should be passed
1823  //! \param blocking specifies whether the object should block when processing input
1824  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1825  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1826  virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
1827 
1828  //! \brief Marks the end of a series of messages on a channel
1829  //! \param channel the channel to signal the end of a series of messages
1830  //! \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed
1831  //! \param blocking specifies whether the object should block when processing input
1832  //! \details Each object that receives the signal will perform its processing, decrement
1833  //! propagation, and then pass the signal on to attached transformations if the value is not 0.
1834  //! \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
1835  //! object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
1836  //! \note There should be a MessageEnd() immediately before MessageSeriesEnd().
1837  virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
1838 
1839  //! \brief Sets the default retrieval channel
1840  //! \param channel the channel to signal the end of a series of messages
1841  //! \note this function may not be implemented in all objects that should support it.
1842  virtual void SetRetrievalChannel(const std::string &channel);
1843  //@}
1844 
1845  //! \name ATTACHMENT
1846  /*! Some BufferedTransformation objects (e.g. Filter objects)
1847  allow other BufferedTransformation objects to be attached. When
1848  this is done, the first object instead of buffering its output,
1849  sends that output to the attached object as input. The entire
1850  attachment chain is deleted when the anchor object is destructed.
1851  */
1852  //@{
1853  //! \brief Determines whether the object allows attachment
1854  //! \returns true if the object allows an attachment, false otherwise
1855  //! \details Sources and Filters will return true, while Sinks and other objects will return false.
1856  virtual bool Attachable() {return false;}
1857 
1858  //! \brief Returns the object immediately attached to this object
1859  //! \details AttachedTransformation returns NULL if there is no attachment
1860  virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;}
1861 
1862  //! \brief Returns the object immediately attached to this object
1863  //! \details AttachedTransformation returns NULL if there is no attachment
1865  {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
1866 
1867  //! \brief Delete the current attachment chain and attach a new one
1868  //! \param newAttachment the new BufferedTransformation to attach
1869  //! \throws NotImplemented
1870  //! \details Detach delete the current attachment chain and replace it with an optional newAttachment
1871  //! \details If a derived class does not override Detach, then the base class throws
1872  //! NotImplemented.
1873  virtual void Detach(BufferedTransformation *newAttachment = 0) {
1874  CRYPTOPP_UNUSED(newAttachment); assert(!Attachable());
1875  throw NotImplemented("BufferedTransformation: this object is not attachable");
1876  }
1877 
1878  //! \brief Add newAttachment to the end of attachment chain
1879  //! \param newAttachment the attachment to add to the end of the chain
1880 
1881  virtual void Attach(BufferedTransformation *newAttachment);
1882  //@}
1883 
1884 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
1885  virtual ~BufferedTransformation() {}
1886 #endif
1887 
1888 protected:
1889  //! \brief Decrements the propagation count while clamping at 0
1890  //! \returns the decremented propagation or 0
1891  static int DecrementPropagation(int propagation)
1892  {return propagation != 0 ? propagation - 1 : 0;}
1893 
1894 private:
1895  byte m_buf[4]; // for ChannelPutWord16 and ChannelPutWord32, to ensure buffer isn't deallocated before non-blocking operation completes
1896 };
1897 
1898 //! \brief An input discarding BufferedTransformation
1899 //! \returns a reference to a BufferedTransformation object that discards all input
1900 CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
1901 
1902 //! \class CryptoMaterial
1903 //! \brief Interface for crypto material, such as public and private keys, and crypto parameters
1904 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
1905 {
1906 public:
1907  //! exception thrown when invalid crypto material is detected
1908  class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
1909  {
1910  public:
1911  explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
1912  };
1913 
1914  //! \brief Assign values to this object
1915  /*! \details This function can be used to create a public key from a private key. */
1916  virtual void AssignFrom(const NameValuePairs &source) =0;
1917 
1918  //! \brief Check this object for errors
1919  //! \param rng a RandomNumberGenerator for objects which use randomized testing
1920  //! \param level the level of thoroughness
1921  //! \returns true if the tests succeed, false otherwise
1922  //! \details There are four levels of thoroughness:
1923  //! <ul>
1924  //! <li>0 - using this object won't cause a crash or exception
1925  //! <li>1 - this object will probably function, and encrypt, sign, other operations correctly
1926  //! <li>2 - ensure this object will function correctly, and perform reasonable security checks
1927  //! <li>3 - perform reasonable security checks, and do checks that may take a long time
1928  //! </ul>
1929  //! \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
1930  //! \details Level 1 may not check for weak keys and such.
1931  //! \details Levels 2 and 3 are recommended.
1932  virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
1933 
1934  //! \brief Check this object for errors
1935  //! \param rng a RandomNumberGenerator for objects which use randomized testing
1936  //! \param level the level of thoroughness
1937  //! \throws InvalidMaterial
1938  //! \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial if validation fails.
1939  virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
1940  {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
1941 
1942  //! \brief Saves a key to a BufferedTransformation
1943  //! \param bt the destination BufferedTransformation
1944  //! \throws NotImplemented
1945  //! \details Save writes the material to a BufferedTransformation.
1946  //! \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
1947  //! includes an object identifier with an algorthm id, like a subjectPublicKeyInfo.
1948  //! \details A "raw" key without the "key info" can be saved using a key's DEREncode method.
1949  //! \details If a derived class does not override Save, then the base class throws
1950  //! NotImplemented.
1951  virtual void Save(BufferedTransformation &bt) const
1952  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
1953 
1954  //! \brief Loads a key from a BufferedTransformation
1955  //! \param bt the source BufferedTransformation
1956  //! \throws KeyingErr
1957  //! \details Load attempts to read material from a BufferedTransformation. If the
1958  //! material is a key that was generated outside the library, then the following
1959  //! usually applies:
1960  //! <ul>
1961  //! <li>the key should be ASN.1 BER encoded
1962  //! <li>the key should be a "key info"
1963  //! </ul>
1964  //! \details "key info" means the key should have an object identifier with an algorthm id,
1965  //! like a subjectPublicKeyInfo.
1966  //! \details To read a "raw" key without the "key info", then call the key's BERDecode method.
1967  //! \note Load generally does not check that the key is valid. Call Validate(), if needed.
1968  virtual void Load(BufferedTransformation &bt)
1969  {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
1970 
1971  //! \brief Determines whether the object supports precomputation
1972  //! \returns true if the object supports precomputation, false otherwise
1973  virtual bool SupportsPrecomputation() const {return false;}
1974 
1975  //! \brief Perform precomputation
1976  //! \param precomputationStorage the suggested number of objects for the precompute table
1977  //! \throws NotImplemented
1978  //! \details The exact semantics of Precompute() varies, but it typically means calculate
1979  //! a table of n objects that can be used later to speed up computation.
1980  //! \details If a derived class does not override Precompute, then the base class throws
1981  //! NotImplemented.
1982  virtual void Precompute(unsigned int precomputationStorage) {
1983  CRYPTOPP_UNUSED(precomputationStorage); assert(!SupportsPrecomputation());
1984  throw NotImplemented("CryptoMaterial: this object does not support precomputation");
1985  }
1986 
1987  //! retrieve previously saved precomputation
1988  virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
1989  {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
1990  //! save precomputation for later use
1991  virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
1992  {CRYPTOPP_UNUSED(storedPrecomputation); assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
1993 
1994  // for internal library use
1995  void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
1996 
1997 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
1998  virtual ~CryptoMaterial() {}
1999 #endif
2000 
2001 #if (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
2002  // Sun Studio 11/CC 5.8 workaround: it generates incorrect code when casting to an empty virtual base class
2003  char m_sunCCworkaround;
2004 #endif
2005 };
2006 
2007 //! \class GeneratableCryptoMaterial
2008 //! \brief Interface for generatable crypto material, such as private keys and crypto parameters
2009 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
2010 {
2011 public:
2012 
2013  //! \brief Generate a random key or crypto parameters
2014  //! \param rng a RandomNumberGenerator to produce keying material
2015  //! \param params additional initialization parameters
2016  //! \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2017  //! \details If a derived class does not override GenerateRandom, then the base class throws
2018  //! NotImplemented.
2020  CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
2021  throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
2022  }
2023 
2024  //! \brief Generate a random key or crypto parameters
2025  //! \param rng a RandomNumberGenerator to produce keying material
2026  //! \param keySize the size of the key, in bits
2027  //! \throws KeyingErr if a key can't be generated or algorithm parameters are invalid
2028  //! \details GenerateRandomWithKeySize calls GenerateRandom with a NameValuePairs
2029  //! object with only "KeySize"
2030  void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
2031 
2032 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2033  virtual ~GeneratableCryptoMaterial() {}
2034 #endif
2035 };
2036 
2037 //! \brief Interface for public keys
2038 
2039 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
2040 {
2041 };
2042 
2043 //! \brief Interface for private keys
2044 
2045 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
2046 {
2047 };
2048 
2049 //! \brief Interface for crypto prameters
2050 
2051 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
2052 {
2053 };
2054 
2055 //! \brief Interface for asymmetric algorithms
2056 
2057 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
2058 {
2059 public:
2060  //! returns a reference to the crypto material used by this object
2061  virtual CryptoMaterial & AccessMaterial() =0;
2062  //! returns a const reference to the crypto material used by this object
2063  virtual const CryptoMaterial & GetMaterial() const =0;
2064 
2065  //! for backwards compatibility, calls AccessMaterial().Load(bt)
2067  {AccessMaterial().Load(bt);}
2068  //! for backwards compatibility, calls GetMaterial().Save(bt)
2070  {GetMaterial().Save(bt);}
2071 
2072 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2073  virtual ~AsymmetricAlgorithm() {}
2074 #endif
2075 };
2076 
2077 //! \brief Interface for asymmetric algorithms using public keys
2078 
2079 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
2080 {
2081 public:
2082  // VC60 workaround: no co-variant return type
2083  CryptoMaterial & AccessMaterial() {return AccessPublicKey();}
2084  const CryptoMaterial & GetMaterial() const {return GetPublicKey();}
2085 
2086  virtual PublicKey & AccessPublicKey() =0;
2087  virtual const PublicKey & GetPublicKey() const {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
2088 
2089 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2090  virtual ~PublicKeyAlgorithm() {}
2091 #endif
2092 };
2093 
2094 //! \brief Interface for asymmetric algorithms using private keys
2095 
2096 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
2097 {
2098 public:
2099  CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
2100  const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
2101 
2102  virtual PrivateKey & AccessPrivateKey() =0;
2103  virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
2104 
2105 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2106  virtual ~PrivateKeyAlgorithm() {}
2107 #endif
2108 };
2109 
2110 //! \brief Interface for key agreement algorithms
2111 
2112 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
2113 {
2114 public:
2115  CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
2116  const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
2117 
2118  virtual CryptoParameters & AccessCryptoParameters() =0;
2119  virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
2120 
2121 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2122  virtual ~KeyAgreementAlgorithm() {}
2123 #endif
2124 };
2125 
2126 //! \brief Interface for public-key encryptors and decryptors
2127 
2128 /*! This class provides an interface common to encryptors and decryptors
2129  for querying their plaintext and ciphertext lengths.
2130 */
2131 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
2132 {
2133 public:
2134  virtual ~PK_CryptoSystem() {}
2135 
2136  //! maximum length of plaintext for a given ciphertext length
2137  /*! \note This function returns 0 if ciphertextLength is not valid (too long or too short). */
2138  virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
2139 
2140  //! calculate length of ciphertext given length of plaintext
2141  /*! \note This function returns 0 if plaintextLength is not valid (too long). */
2142  virtual size_t CiphertextLength(size_t plaintextLength) const =0;
2143 
2144  //! this object supports the use of the parameter with the given name
2145  /*! some possible parameter names: EncodingParameters, KeyDerivationParameters */
2146  virtual bool ParameterSupported(const char *name) const =0;
2147 
2148  //! return fixed ciphertext length, if one exists, otherwise return 0
2149  /*! \note "Fixed" here means length of ciphertext does not depend on length of plaintext.
2150  It usually does depend on the key length. */
2151  virtual size_t FixedCiphertextLength() const {return 0;}
2152 
2153  //! return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0
2154  virtual size_t FixedMaxPlaintextLength() const {return 0;}
2155 
2156 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
2157  size_t MaxPlainTextLength(size_t cipherTextLength) const {return MaxPlaintextLength(cipherTextLength);}
2158  size_t CipherTextLength(size_t plainTextLength) const {return CiphertextLength(plainTextLength);}
2159 #endif
2160 };
2161 
2162 //! \class PK_Encryptor
2163 //! \brief Interface for public-key encryptors
2164 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
2165 {
2166 public:
2167  //! \brief Exception thrown when trying to encrypt plaintext of invalid length
2168  class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
2169  {
2170  public:
2171  InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
2172  };
2173 
2174  //! \brief Encrypt a byte string
2175  //! \param rng a RandomNumberGenerator derived class
2176  //! \param plaintext the plaintext byte buffer
2177  //! \param plaintextLength the size of the plaintext byte buffer
2178  //! \param ciphertext a byte buffer to hold the encrypted string
2179  //! \param parameters additional configuration options
2180  //! \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
2181  //! \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
2182  //! byte buffer is large enough.
2183  //! \sa PK_Decryptor
2184  virtual void Encrypt(RandomNumberGenerator &rng,
2185  const byte *plaintext, size_t plaintextLength,
2186  byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2187 
2188  //! \brief Create a new encryption filter
2189  //! \note The caller is responsible for deleting the returned pointer.
2190  //! \note Encoding parameters should be passed in the "EP" channel.
2191  virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
2192  BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2193 };
2194 
2195 //! \class PK_Decryptor
2196 //! \brief Interface for public-key decryptors
2197 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
2198 {
2199 public:
2200  //! \brief Decrypt a byte string
2201  //! \param rng a RandomNumberGenerator derived class
2202  //! \param ciphertext the encrypted byte buffer
2203  //! \param ciphertextLength the size of the encrypted byte buffer
2204  //! \param plaintext a byte buffer to hold the decrypted string
2205  //! \param parameters additional configuration options
2206  //! \returns the result of the decryption operation
2207  //! \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
2208  //! byte buffer is large enough
2209  //! \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
2210  //! is valid and holds the the actual length of the plaintext recovered.
2211  //! on success. The result is undefined if decryption failed. If DecodingResult::isValidCoding
2212  //! is false, then DecodingResult::messageLength is undefined.
2213  //! \sa PK_Encryptor
2214  virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
2215  const byte *ciphertext, size_t ciphertextLength,
2216  byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2217 
2218  //! create a new decryption filter
2219  /*! \note caller is responsible for deleting the returned pointer
2220  */
2221  virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
2222  BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2223 
2224  //! decrypt a fixed size ciphertext
2225  DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
2226  {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
2227 
2228 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2229  virtual ~PK_Decryptor() {}
2230 #endif
2231 };
2232 
2233 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
2234 typedef PK_CryptoSystem PK_FixedLengthCryptoSystem;
2235 typedef PK_Encryptor PK_FixedLengthEncryptor;
2236 typedef PK_Decryptor PK_FixedLengthDecryptor;
2237 #endif
2238 
2239 //! \brief Interface for public-key signers and verifiers
2240 
2241 /*! This class provides an interface common to signers and verifiers
2242  for querying scheme properties.
2243 */
2244 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
2245 {
2246 public:
2247  //! 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
2248  class CRYPTOPP_DLL InvalidKeyLength : public Exception
2249  {
2250  public:
2251  InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
2252  };
2253 
2254  //! 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
2255  class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
2256  {
2257  public:
2258  KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
2259  };
2260 
2261  virtual ~PK_SignatureScheme() {}
2262 
2263  //! signature length if it only depends on the key, otherwise 0
2264  virtual size_t SignatureLength() const =0;
2265 
2266  //! maximum signature length produced for a given length of recoverable message part
2267  virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
2268  {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
2269 
2270  //! length of longest message that can be recovered, or 0 if this signature scheme does not support message recovery
2271  virtual size_t MaxRecoverableLength() const =0;
2272 
2273  //! 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
2274  virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
2275 
2276  //! requires a random number generator to sign
2277  /*! if this returns false, NullRNG() can be passed to functions that take RandomNumberGenerator & */
2278  virtual bool IsProbabilistic() const =0;
2279 
2280  //! whether or not a non-recoverable message part can be signed
2281  virtual bool AllowNonrecoverablePart() const =0;
2282 
2283  //! if this function returns true, during verification you must input the signature before the message, otherwise you can input it at anytime */
2284  virtual bool SignatureUpfront() const {return false;}
2285 
2286  //! whether you must input the recoverable part before the non-recoverable part during signing
2287  virtual bool RecoverablePartFirst() const =0;
2288 };
2289 
2290 //! \brief Interface for accumulating messages to be signed or verified
2291 /*! Only Update() should be called
2292  on this class. No other functions inherited from HashTransformation should be called.
2293 */
2294 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
2295 {
2296 public:
2297  //! should not be called on PK_MessageAccumulator
2298  unsigned int DigestSize() const
2299  {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
2300 
2301  //! should not be called on PK_MessageAccumulator
2302  void TruncatedFinal(byte *digest, size_t digestSize)
2303  {
2304  CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
2305  throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
2306  }
2307 };
2308 
2309 //! \brief Interface for public-key signers
2310 
2311 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
2312 {
2313 public:
2314  //! create a new HashTransformation to accumulate the message to be signed
2315  virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
2316 
2317  virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
2318 
2319  //! sign and delete messageAccumulator (even in case of exception thrown)
2320  /*! \pre size of signature == MaxSignatureLength()
2321  \returns actual signature length
2322  */
2323  virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
2324 
2325  //! sign and restart messageAccumulator
2326  /*! \pre size of signature == MaxSignatureLength()
2327  \returns actual signature length
2328  */
2329  virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
2330 
2331  //! sign a message
2332  /*! \pre size of signature == MaxSignatureLength()
2333  \returns actual signature length
2334  */
2335  virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
2336 
2337  //! sign a recoverable message
2338  /*! \pre size of signature == MaxSignatureLength(recoverableMessageLength)
2339  \returns actual signature length
2340  */
2341  virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
2342  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
2343 
2344 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2345  virtual ~PK_Signer() {}
2346 #endif
2347 };
2348 
2349 //! \brief Interface for public-key signature verifiers
2350 /*! The Recover* functions throw NotImplemented if the signature scheme does not support
2351  message recovery.
2352  The Verify* functions throw InvalidDataFormat if the scheme does support message
2353  recovery and the signature contains a non-empty recoverable message part. The
2354  Recovery* functions should be used in that case.
2355 */
2356 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
2357 {
2358 public:
2359  //! create a new HashTransformation to accumulate the message to be verified
2360  virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
2361 
2362  //! input signature into a message accumulator
2363  virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
2364 
2365  //! check whether messageAccumulator contains a valid signature and message, and delete messageAccumulator (even in case of exception thrown)
2366  virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
2367 
2368  //! check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
2369  virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
2370 
2371  //! check whether input signature is a valid signature for input message
2372  virtual bool VerifyMessage(const byte *message, size_t messageLen,
2373  const byte *signature, size_t signatureLength) const;
2374 
2375  //! recover a message from its signature
2376  /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
2377  */
2378  virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
2379 
2380  //! recover a message from its signature
2381  /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
2382  */
2383  virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
2384 
2385  //! recover a message from its signature
2386  /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
2387  */
2388  virtual DecodingResult RecoverMessage(byte *recoveredMessage,
2389  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
2390  const byte *signature, size_t signatureLength) const;
2391 
2392 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2393  virtual ~PK_Verifier() {}
2394 #endif
2395 };
2396 
2397 //! \brief Interface for domains of simple key agreement protocols
2398 
2399 /*! A key agreement domain is a set of parameters that must be shared
2400  by two parties in a key agreement protocol, along with the algorithms
2401  for generating key pairs and deriving agreed values.
2402 */
2403 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
2404 {
2405 public:
2406  //! return length of agreed value produced
2407  virtual unsigned int AgreedValueLength() const =0;
2408  //! return length of private keys in this domain
2409  virtual unsigned int PrivateKeyLength() const =0;
2410  //! return length of public keys in this domain
2411  virtual unsigned int PublicKeyLength() const =0;
2412  //! generate private key
2413  /*! \pre size of privateKey == PrivateKeyLength() */
2414  virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
2415  //! generate public key
2416  /*! re size of publicKey == PublicKeyLength() */
2417  virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
2418  //! generate private/public key pair
2419  /*! \note equivalent to calling GeneratePrivateKey() and then GeneratePublicKey() */
2420  virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
2421  //! derive agreed value from your private key and couterparty's public key, return false in case of failure
2422  /*! \note If you have previously validated the public key, use validateOtherPublicKey=false to save time.
2423  re size of agreedValue == AgreedValueLength()
2424  \pre length of privateKey == PrivateKeyLength()
2425  \pre length of otherPublicKey == PublicKeyLength()
2426  */
2427  virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
2428 
2429 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2430  virtual ~SimpleKeyAgreementDomain() {}
2431 #endif
2432 
2433 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
2434  bool ValidateDomainParameters(RandomNumberGenerator &rng) const
2435  {return GetCryptoParameters().Validate(rng, 2);}
2436 #endif
2437 };
2438 
2439 //! \brief Interface for domains of authenticated key agreement protocols
2440 
2441 /*! In an authenticated key agreement protocol, each party has two
2442  key pairs. The long-lived key pair is called the static key pair,
2443  and the short-lived key pair is called the ephemeral key pair.
2444 */
2445 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
2446 {
2447 public:
2448  //! return length of agreed value produced
2449  virtual unsigned int AgreedValueLength() const =0;
2450 
2451  //! return length of static private keys in this domain
2452  virtual unsigned int StaticPrivateKeyLength() const =0;
2453  //! return length of static public keys in this domain
2454  virtual unsigned int StaticPublicKeyLength() const =0;
2455  //! generate static private key
2456  /*! \pre size of privateKey == PrivateStaticKeyLength() */
2457  virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
2458  //! generate static public key
2459  /*! re size of publicKey == PublicStaticKeyLength() */
2460  virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
2461  //! generate private/public key pair
2462  /*! \note equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey() */
2463  virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
2464 
2465  //! return length of ephemeral private keys in this domain
2466  virtual unsigned int EphemeralPrivateKeyLength() const =0;
2467  //! return length of ephemeral public keys in this domain
2468  virtual unsigned int EphemeralPublicKeyLength() const =0;
2469  //! \brief Generate ephemeral private key
2470  //! \pre size of privateKey == PrivateEphemeralKeyLength()
2471  virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
2472  //! \brief Generate ephemeral public key
2473  //! \pre size of publicKey == PublicEphemeralKeyLength()
2474  virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
2475  //! \brief Generate private/public key pair
2476  /*! \note equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() */
2477  virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
2478 
2479  //! \brief Derive agreed value
2480  //! \returns true upon success, false in case of failure
2481  //! \details Agree() derives an agreed value from your private keys and couterparty's public keys
2482  //! \details The ephemeral public key will always be validated. If you have previously validated the
2483  //! static public key, use validateStaticOtherPublicKey=false to save time.
2484  //! \pre size of agreedValue == AgreedValueLength()
2485  //! \pre length of staticPrivateKey == StaticPrivateKeyLength()
2486  //! \pre length of ephemeralPrivateKey == EphemeralPrivateKeyLength()
2487  //! \pre length of staticOtherPublicKey == StaticPublicKeyLength()
2488  //! \pre length of ephemeralOtherPublicKey == EphemeralPublicKeyLength()
2489  virtual bool Agree(byte *agreedValue,
2490  const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
2491  const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
2492  bool validateStaticOtherPublicKey=true) const =0;
2493 
2494 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2495  virtual ~AuthenticatedKeyAgreementDomain() {}
2496 #endif
2497 
2498 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
2499  bool ValidateDomainParameters(RandomNumberGenerator &rng) const
2500  {return GetCryptoParameters().Validate(rng, 2);}
2501 #endif
2502 };
2503 
2504 // interface for password authenticated key agreement protocols, not implemented yet
2505 #if 0
2506 //! \brief Interface for protocol sessions
2507 /*! The methods should be called in the following order:
2508 
2509  InitializeSession(rng, parameters); // or call initialize method in derived class
2510  while (true)
2511  {
2512  if (OutgoingMessageAvailable())
2513  {
2514  length = GetOutgoingMessageLength();
2515  GetOutgoingMessage(message);
2516  ; // send outgoing message
2517  }
2518 
2519  if (LastMessageProcessed())
2520  break;
2521 
2522  ; // receive incoming message
2523  ProcessIncomingMessage(message);
2524  }
2525  ; // call methods in derived class to obtain result of protocol session
2526 */
2527 class ProtocolSession
2528 {
2529 public:
2530  //! exception thrown when an invalid protocol message is processed
2531  class ProtocolError : public Exception
2532  {
2533  public:
2534  ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
2535  };
2536 
2537  //! exception thrown when a function is called unexpectedly
2538  /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
2539  class UnexpectedMethodCall : public Exception
2540  {
2541  public:
2542  UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
2543  };
2544 
2545  ProtocolSession() : m_rng(NULL), m_throwOnProtocolError(true), m_validState(false) {}
2546  virtual ~ProtocolSession() {}
2547 
2548  virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
2549 
2550  bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
2551  void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
2552 
2553  bool HasValidState() const {return m_validState;}
2554 
2555  virtual bool OutgoingMessageAvailable() const =0;
2556  virtual unsigned int GetOutgoingMessageLength() const =0;
2557  virtual void GetOutgoingMessage(byte *message) =0;
2558 
2559  virtual bool LastMessageProcessed() const =0;
2560  virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
2561 
2562 protected:
2563  void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
2564  void CheckAndHandleInvalidState() const;
2565  void SetValidState(bool valid) {m_validState = valid;}
2566 
2567  RandomNumberGenerator *m_rng;
2568 
2569 private:
2570  bool m_throwOnProtocolError, m_validState;
2571 };
2572 
2573 class KeyAgreementSession : public ProtocolSession
2574 {
2575 public:
2576  virtual unsigned int GetAgreedValueLength() const =0;
2577  virtual void GetAgreedValue(byte *agreedValue) const =0;
2578 
2579 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2580  virtual ~KeyAgreementSession() {}
2581 #endif
2582 };
2583 
2584 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
2585 {
2586 public:
2587  void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
2588  const byte *myId, unsigned int myIdLength,
2589  const byte *counterPartyId, unsigned int counterPartyIdLength,
2590  const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
2591 
2592 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2593  virtual ~PasswordAuthenticatedKeyAgreementSession() {}
2594 #endif
2595 };
2596 
2597 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
2598 {
2599 public:
2600  //! return whether the domain parameters stored in this object are valid
2601  virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
2602  {return GetCryptoParameters().Validate(rng, 2);}
2603 
2604  virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
2605  virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
2606 
2607  enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
2608 
2609  virtual bool IsValidRole(unsigned int role) =0;
2610  virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
2611 
2612 #ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
2613  virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
2614 #endif
2615 };
2616 #endif
2617 
2618 //! \brief Exception thrown when an ASN1 BER decoing error is encountered
2619 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
2620 {
2621 public:
2622  BERDecodeErr() : InvalidArgument("BER decode error") {}
2623  BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
2624 };
2625 
2626 //! \brief Interface for encoding and decoding ASN1 objects
2627 //! \details Each class that derives from ASN1Object should provide a serialization format
2628 //! that controls subobject layout. Most of the time the serialization format is
2629 //! taken from a standard, like P1363 or an RFC.
2630 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
2631 {
2632 public:
2633  virtual ~ASN1Object() {}
2634 
2635  //! \brief Decode this object from a BufferedTransformation
2636  //! \param bt BufferedTransformation object
2637  //! \details Uses Basic Encoding Rules (BER)
2638  virtual void BERDecode(BufferedTransformation &bt) =0;
2639 
2640  //! \brief Encode this object into a BufferedTransformation
2641  //! \param bt BufferedTransformation object
2642  //! \details Uses Distinguished Encoding Rules (DER)
2643  virtual void DEREncode(BufferedTransformation &bt) const =0;
2644 
2645  //! \brief Encode this object into a BufferedTransformation
2646  //! \param bt BufferedTransformation object
2647  //! \details Uses Basic Encoding Rules (BER).
2648  //! \details This may be useful if DEREncode() would be too inefficient.
2649  virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
2650 };
2651 
2652 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
2653 typedef PK_SignatureScheme PK_SignatureSystem;
2654 typedef SimpleKeyAgreementDomain PK_SimpleKeyAgreementDomain;
2655 typedef AuthenticatedKeyAgreementDomain PK_AuthenticatedKeyAgreementDomain;
2656 #endif
2657 
2658 NAMESPACE_END
2659 
2660 #if CRYPTOPP_MSC_VERSION
2661 # pragma warning(pop)
2662 #endif
2663 
2664 #endif
virtual unsigned int BlockSize() const
Provides the block size of the compression function.
Definition: cryptlib.h:907
Base class for all exceptions thrown by Crypto++.
Definition: cryptlib.h:124
void DEREncode(BufferedTransformation &bt) const
for backwards compatibility, calls GetMaterial().Save(bt)
Definition: cryptlib.h:2069
exception thrown when invalid crypto material is detected
Definition: cryptlib.h:1908
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition: cryptlib.h:1982
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
unsigned int TagSize() const
Provides the tag size of the hash.
Definition: cryptlib.h:901
Interface for message authentication codes.
Definition: cryptlib.h:1027
ErrorType
error types
Definition: cryptlib.h:128
container of wait objects
Definition: wait.h:151
Interface for asymmetric algorithms.
Definition: cryptlib.h:2057
virtual unsigned int MinIVLength() const
returns minimal length of IVs accepted by this object
Definition: cryptlib.h:588
virtual bool NeedsPrespecifiedDataLengths() const
if this function returns true, SpecifyDataLengths() must be called before attempting to input data ...
Definition: cryptlib.h:1055
Interface for public-key encryptors and decryptors.
Definition: cryptlib.h:2131
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:116
const char * what() const
Retrieves a C-string describing the exception.
Definition: cryptlib.h:150
virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition: cryptlib.h:1939
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
const std::type_info & GetStoredTypeInfo() const
Provides the stored type.
Definition: cryptlib.h:282
virtual void Load(BufferedTransformation &bt)
Loads a key from a BufferedTransformation.
Definition: cryptlib.h:1968
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition: cryptlib.h:1726
Exception(ErrorType errorType, const std::string &s)
Construct a new Exception.
Definition: cryptlib.h:146
virtual void IsolatedInitialize(const NameValuePairs &parameters)
Initialize or reinitialize this object, without signal propagation.
Definition: cryptlib.h:1394
this indicates that a member function was called in the wrong state, for example trying to encrypt a ...
Definition: cryptlib.h:1040
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
Definition: cryptlib.h:2116
Interface for public-key signers.
Definition: cryptlib.h:2311
Interface for public-key encryptors.
Definition: cryptlib.h:2164
virtual bool CanModifyInput() const
Determines whether input can be modifed by the callee.
Definition: cryptlib.h:1310
Converts a typename to an enumerated value.
Definition: cryptlib.h:110
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
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:2066
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const
decrypt a fixed size ciphertext
Definition: cryptlib.h:2225
Flush(true) was called but it can&#39;t completely flush its buffers.
Definition: cryptlib.h:194
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:2099
Interface for asymmetric algorithms using private keys.
Definition: cryptlib.h:2096
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
ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
Construct a ValueTypeMismatch.
Definition: cryptlib.h:276
virtual Clonable * Clone() const
Copies this object.
Definition: cryptlib.h:464
CipherDir GetCipherDirection() const
Definition: cryptlib.h:742
Library configuration file.
Interface for random number generators.
Definition: cryptlib.h:1085
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 int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1456
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this hash.
Definition: cryptlib.h:914
Interface for buffered transformations.
Definition: cryptlib.h:1248
Interface for private keys.
Definition: cryptlib.h:2045
virtual const BufferedTransformation * AttachedTransformation() const
Returns the object immediately attached to this object.
Definition: cryptlib.h:1864
Interface for cloning objects.
Definition: cryptlib.h:454
virtual size_t FixedCiphertextLength() const
return fixed ciphertext length, if one exists, otherwise return 0
Definition: cryptlib.h:2151
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:1574
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:1194
size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
Input multiple bytes that may be modified by callee.
Definition: cryptlib.h:1319
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
save precomputation for later use
Definition: cryptlib.h:1991
const std::type_info & GetRetrievingTypeInfo() const
Provides the retrieveing type.
Definition: cryptlib.h:286
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:1736
bool MessageEnd(int propagation=-1, bool blocking=true)
Signals the end of messages to the object.
Definition: cryptlib.h:1327
Interface for domains of simple key agreement protocols.
Definition: cryptlib.h:2403
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
Definition: cryptlib.h:2100
bool CanUsePredictableIVs() const
returns whether the object can use random but possibly predictable IVs (in addition to ones returned ...
Definition: cryptlib.h:577
Exception thrown when a filter does not support named channels.
Definition: cryptlib.h:1714
Returns a decoding results.
Definition: cryptlib.h:220
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
retrieve previously saved precomputation
Definition: cryptlib.h:1988
Exception thrown when trying to encrypt plaintext of invalid length.
Definition: cryptlib.h:2168
Input data was received that did not conform to expected format.
Definition: cryptlib.h:138
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:1544
Interface for public-key decryptors.
Definition: cryptlib.h:2197
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:2255
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1269
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.cpp:41
bool operator!=(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition: cryptlib.h:238
virtual void Restart()
Restart the hash.
Definition: cryptlib.h:890
virtual unsigned int MaxIVLength() const
returns maximal length of IVs accepted by this object
Definition: cryptlib.h:590
unsigned int DigestSize() const
should not be called on PK_MessageAccumulator
Definition: cryptlib.h:2298
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:515
Interface for encoding and decoding ASN1 objects.
Definition: cryptlib.h:2630
StreamTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:758
virtual void Resynchronize(const byte *iv, int ivLength=-1)
resynchronize with an IV. ivLength=-1 means use IVSize()
Definition: cryptlib.h:592
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:762
void ProcessString(byte *outString, const byte *inString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:809
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 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:1746
DecodingResult()
Constructs a DecodingResult.
Definition: cryptlib.h:224
Exception thrown when a filter does not recognize a named channel.
Definition: cryptlib.h:1717
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode...
Definition: cryptlib.h:1020
Multiple precision integer with arithmetic operations.
Definition: integer.h:31
DecodingResult(size_t len)
Constructs a DecodingResult.
Definition: cryptlib.h:228
void ProcessBlock(const byte *inBlock, byte *outBlock) const
Encrypt or decrypt a block.
Definition: cryptlib.h:685
invalid key exception, may be thrown by any function in this class if the private or public key has a...
Definition: cryptlib.h:2248
Interface for algorithms that take byte strings as keys.
Definition: cryptlib.h:497
bool operator==(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition: cryptlib.h:233
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:1860
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:1452
Interface for asymmetric algorithms using public keys.
Definition: cryptlib.h:2079
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:583
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.cpp:79
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
Definition: cryptlib.h:1104
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 public-key signers and verifiers.
Definition: cryptlib.h:2244
Interface for the data processing portion of stream ciphers.
Definition: cryptlib.h:752
const std::string & GetOperation() const
Retrieve the operating system API that reported the error.
Definition: cryptlib.h:209
virtual bool Verify(const byte *digest)
Verifies the hash of the current message.
Definition: cryptlib.h:938
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:488
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
int GetErrorCode() const
Retrieve the error code returned by the operating system.
Definition: cryptlib.h:211
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:1408
const unsigned long INFINITE_TIME
Represents infinite time.
Definition: cryptlib.h:105
ErrorType GetErrorType() const
Retrieves the error type for the exception.
Definition: cryptlib.h:156
void GetRequiredParameter(const char *className, const char *name, T &value) const
Retrieves a required name/value pair.
Definition: cryptlib.h:390
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:1278
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2294
unsigned int DefaultIVLength() const
returns default length of IVs accepted by this object
Definition: cryptlib.h:586
virtual void Detach(BufferedTransformation *newAttachment=0)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:1873
A decryption filter encountered invalid ciphertext.
Definition: cryptlib.h:180
Interface for key agreement algorithms.
Definition: cryptlib.h:2112
thrown by objects that have not implemented nonblocking input processing
Definition: cryptlib.h:1360
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
virtual void Seek(lword pos)
Seek to an absolute position.
Definition: cryptlib.h:827
void ProcessBlock(byte *inoutBlock) const
Encrypt or decrypt a block in place.
Definition: cryptlib.h:694
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:2083
Interface for public-key signature verifiers.
Definition: cryptlib.h:2356
virtual bool IsPermutation() const
returns true if this is a permutation (i.e. there is an inverse transformation)
Definition: cryptlib.h:706
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
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:1561
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:1904
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1304
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2019
CryptoMaterial & AccessMaterial()
returns a reference to the crypto material used by this object
Definition: cryptlib.h:2115
An invalid argument was detected.
Definition: cryptlib.h:132
Interface for generatable crypto material, such as private keys and crypto parameters.
Definition: cryptlib.h:2009
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:1339
Interface for crypto prameters.
Definition: cryptlib.h:2051
bool GetThisPointer(T *&ptr) const
Get a pointer to this object.
Definition: cryptlib.h:306
bool isValidCoding
Flag to indicate the decoding is valid.
Definition: cryptlib.h:241
BufferedTransformation & Ref()
Provides a reference to this object.
Definition: cryptlib.h:1259
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
Interface for public keys.
Definition: cryptlib.h:2039
Crypto++ library namespace.
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:319
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
bool IsResynchronizable() const
returns whether the object can be resynchronized (i.e. supports initialization vectors) ...
Definition: cryptlib.h:573
Interface for domains of authenticated key agreement protocols.
Definition: cryptlib.h:2445
void TruncatedFinal(byte *digest, size_t digestSize)
should not be called on PK_MessageAccumulator
Definition: cryptlib.h:2302
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:1622
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
virtual void BEREncode(BufferedTransformation &bt) const
Encode this object into a BufferedTransformation.
Definition: cryptlib.h:2649
Error reading from input device or writing to output device.
Definition: cryptlib.h:140
virtual void Save(BufferedTransformation &bt) const
Saves a key to a BufferedTransformation.
Definition: cryptlib.h:1951
virtual bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition: cryptlib.h:1973
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:1788
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:1356
unsigned int GetByte(ByteOrder order, T value, unsigned int index)
Gets a byte from a value.
Definition: misc.h:1549
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 lword MaxFooterLength() const
the maximum length of AAD that can be input after the encrypted data
Definition: cryptlib.h:1052
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this cipher.
Definition: cryptlib.h:769
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
Definition: cryptlib.h:2084
virtual size_t MaxSignatureLength(size_t recoverablePartLength=0) const
maximum signature length produced for a given length of recoverable message part
Definition: cryptlib.h:2267
virtual bool Attachable()
Determines whether the object allows attachment.
Definition: cryptlib.h:1856
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 bool SignatureUpfront() const
if this function returns true, during verification you must input the signature before the message...
Definition: cryptlib.h:2284
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: cryptlib.h:1096
virtual size_t FixedMaxPlaintextLength() const
return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0 ...
Definition: cryptlib.h:2154
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition: cryptlib.h:1775
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
Interface for retrieving values given their names.
Definition: cryptlib.h:261
Exception thrown when an ASN1 BER decoing error is encountered.
Definition: cryptlib.h:2619
The IV must be random.
Definition: cryptlib.h:559
virtual unsigned int OptimalNumberOfParallelBlocks() const
Determines the number of blocks that can be processed in parallel.
Definition: cryptlib.h:716
const std::string & GetWhat() const
Retrieves a string describing the exception.
Definition: cryptlib.h:152