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