Crypto++
cryptlib.h
Go to the documentation of this file.
1 // cryptlib.h - written and placed in the public domain by Wei Dai
2 /*! \file
3  This file contains the declarations for the abstract base
4  classes that provide a uniform interface to this library.
5 */
6 
7 /*! \mainpage Crypto++ Library 5.6.1 API Reference
8 <dl>
9 <dt>Abstract Base Classes<dd>
10  cryptlib.h
11 <dt>Authenticated Encryption<dd>
12  AuthenticatedSymmetricCipherDocumentation
13 <dt>Symmetric Ciphers<dd>
14  SymmetricCipherDocumentation
15 <dt>Hash Functions<dd>
16  SHA1, SHA224, SHA256, SHA384, SHA512, Tiger, Whirlpool, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, Weak1::MD2, Weak1::MD4, Weak1::MD5
17 <dt>Non-Cryptographic Checksums<dd>
18  CRC32, Adler32
19 <dt>Message Authentication Codes<dd>
20  VMAC, HMAC, CBC_MAC, CMAC, DMAC, TTMAC, GCM (GMAC)
21 <dt>Random Number Generators<dd>
22  NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG, #DefaultAutoSeededRNG
23 <dt>Password-based Cryptography<dd>
24  PasswordBasedKeyDerivationFunction
25 <dt>Public Key Cryptosystems<dd>
26  DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
27 <dt>Public Key Signature Schemes<dd>
28  DSA, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, RabinSS, RWSS, ESIGN
29 <dt>Key Agreement<dd>
30  #DH, DH2, #MQV, ECDH, ECMQV, XTR_DH
31 <dt>Algebraic Structures<dd>
32  Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
33  ModularArithmetic, MontgomeryRepresentation, GFP2_ONB,
34  GF2NP, GF256, GF2_32, EC2N, ECP
35 <dt>Secret Sharing and Information Dispersal<dd>
36  SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
37 <dt>Compression<dd>
38  Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
39 <dt>Input Source Classes<dd>
40  StringSource, #ArraySource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource
41 <dt>Output Sink Classes<dd>
42  StringSinkTemplate, ArraySink, FileSink, SocketSink, WindowsPipeSink, RandomNumberSink
43 <dt>Filter Wrappers<dd>
44  StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter
45 <dt>Binary to Text Encoders and Decoders<dd>
46  HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base32Encoder, Base32Decoder
47 <dt>Wrappers for OS features<dd>
48  Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer
49 <dt>FIPS 140 related<dd>
50  fips140.h
51 </dl>
52 
53 In the DLL version of Crypto++, only the following implementation class are available.
54 <dl>
55 <dt>Block Ciphers<dd>
56  AES, DES_EDE2, DES_EDE3, SKIPJACK
57 <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
58  ECB_Mode<BC>, CTR_Mode<BC>, CBC_Mode<BC>, CFB_FIPS_Mode<BC>, OFB_Mode<BC>, GCM<AES>
59 <dt>Hash Functions<dd>
60  SHA1, SHA224, SHA256, SHA384, SHA512
61 <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
62  RSASS<PKCS1v15, H>, RSASS<PSS, H>, RSASS_ISO<H>, RWSS<P1363_EMSA2, H>, DSA, ECDSA<ECP, H>, ECDSA<EC2N, H>
63 <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
64  HMAC<H>, CBC_MAC<DES_EDE2>, CBC_MAC<DES_EDE3>, GCM<AES>
65 <dt>Random Number Generators<dd>
66  #DefaultAutoSeededRNG (AutoSeededX917RNG<AES>)
67 <dt>Key Agreement<dd>
68  #DH
69 <dt>Public Key Cryptosystems<dd>
70  RSAES<OAEP<SHA1> >
71 </dl>
72 
73 <p>This reference manual is a work in progress. Some classes are still lacking detailed descriptions.
74 <p>Thanks to Ryan Phillips for providing the Doxygen configuration file
75 and getting me started with this manual.
76 */
77 
78 #ifndef CRYPTOPP_CRYPTLIB_H
79 #define CRYPTOPP_CRYPTLIB_H
80 
81 #include "config.h"
82 #include "stdcpp.h"
83 
84 NAMESPACE_BEGIN(CryptoPP)
85 
86 // forward declarations
87 class Integer;
90 
91 //! used to specify a direction for a cipher to operate in (encrypt or decrypt)
92 enum CipherDir {ENCRYPTION, DECRYPTION};
93 
94 //! used to represent infinite time
95 const unsigned long INFINITE_TIME = ULONG_MAX;
96 
97 // VC60 workaround: using enums as template parameters causes problems
98 template <typename ENUM_TYPE, int VALUE>
99 struct EnumToType
100 {
101  static ENUM_TYPE ToEnum() {return (ENUM_TYPE)VALUE;}
102 };
103 
104 enum ByteOrder {LITTLE_ENDIAN_ORDER = 0, BIG_ENDIAN_ORDER = 1};
107 
108 //! base class for all exceptions thrown by Crypto++
109 class CRYPTOPP_DLL Exception : public std::exception
110 {
111 public:
112  //! error types
113  enum ErrorType {
114  //! a method is not implemented
116  //! invalid function argument
118  //! BufferedTransformation received a Flush(true) signal but can't flush buffers
120  //! data integerity check (such as CRC or MAC) failed
122  //! received input data that doesn't conform to expected format
124  //! error reading from input device or writing to output device
126  //! some error not belong to any of the above categories
127  OTHER_ERROR
128  };
129 
130  explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
131  virtual ~Exception() throw() {}
132  const char *what() const throw() {return (m_what.c_str());}
133  const std::string &GetWhat() const {return m_what;}
134  void SetWhat(const std::string &s) {m_what = s;}
135  ErrorType GetErrorType() const {return m_errorType;}
136  void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
137 
138 private:
139  ErrorType m_errorType;
140  std::string m_what;
141 };
142 
143 //! exception thrown when an invalid argument is detected
144 class CRYPTOPP_DLL InvalidArgument : public Exception
145 {
146 public:
147  explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
148 };
149 
150 //! exception thrown when input data is received that doesn't conform to expected format
151 class CRYPTOPP_DLL InvalidDataFormat : public Exception
152 {
153 public:
154  explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
155 };
156 
157 //! exception thrown by decryption filters when trying to decrypt an invalid ciphertext
158 class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
159 {
160 public:
161  explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
162 };
163 
164 //! exception thrown by a class if a non-implemented method is called
165 class CRYPTOPP_DLL NotImplemented : public Exception
166 {
167 public:
168  explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
169 };
170 
171 //! exception thrown by a class when Flush(true) is called but it can't completely flush its buffers
172 class CRYPTOPP_DLL CannotFlush : public Exception
173 {
174 public:
175  explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
176 };
177 
178 //! error reported by the operating system
179 class CRYPTOPP_DLL OS_Error : public Exception
180 {
181 public:
182  OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
183  : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
184  ~OS_Error() throw() {}
185 
186  // the operating system API that reported the error
187  const std::string & GetOperation() const {return m_operation;}
188  // the error code return by the operating system
189  int GetErrorCode() const {return m_errorCode;}
190 
191 protected:
192  std::string m_operation;
193  int m_errorCode;
194 };
195 
196 //! used to return decoding results
197 struct CRYPTOPP_DLL DecodingResult
198 {
199  explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
200  explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
201 
202  bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
203  bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
204 
205  bool isValidCoding;
206  size_t messageLength;
207 
208 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
209  operator size_t() const {return isValidCoding ? messageLength : 0;}
210 #endif
211 };
212 
213 //! interface for retrieving values given their names
214 /*! \note This class is used to safely pass a variable number of arbitrarily typed arguments to functions
215  and to read values from keys and crypto parameters.
216  \note To obtain an object that implements NameValuePairs for the purpose of parameter
217  passing, use the MakeParameters() function.
218  \note To get a value from NameValuePairs, you need to know the name and the type of the value.
219  Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports.
220  Then look at the Name namespace documentation to see what the type of each value is, or
221  alternatively, call GetIntValue() with the value name, and if the type is not int, a
222  ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object.
223 */
224 class CRYPTOPP_NO_VTABLE NameValuePairs
225 {
226 public:
227  virtual ~NameValuePairs() {}
228 
229  //! exception thrown when trying to retrieve a value using a different type than expected
230  class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
231  {
232  public:
233  ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
234  : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
235  , m_stored(stored), m_retrieving(retrieving) {}
236 
237  const std::type_info & GetStoredTypeInfo() const {return m_stored;}
238  const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
239 
240  private:
241  const std::type_info &m_stored;
242  const std::type_info &m_retrieving;
243  };
244 
245  //! get a copy of this object or a subobject of it
246  template <class T>
247  bool GetThisObject(T &object) const
248  {
249  return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
250  }
251 
252  //! get a pointer to this object, as a pointer to T
253  template <class T>
254  bool GetThisPointer(T *&p) const
255  {
256  return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), p);
257  }
258 
259  //! get a named value, returns true if the name exists
260  template <class T>
261  bool GetValue(const char *name, T &value) const
262  {
263  return GetVoidValue(name, typeid(T), &value);
264  }
265 
266  //! get a named value, returns the default if the name doesn't exist
267  template <class T>
268  T GetValueWithDefault(const char *name, T defaultValue) const
269  {
270  GetValue(name, defaultValue);
271  return defaultValue;
272  }
273 
274  //! get a list of value names that can be retrieved
275  CRYPTOPP_DLL std::string GetValueNames() const
276  {std::string result; GetValue("ValueNames", result); return result;}
277 
278  //! get a named value with type int
279  /*! used to ensure we don't accidentally try to get an unsigned int
280  or some other type when we mean int (which is the most common case) */
281  CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
282  {return GetValue(name, value);}
283 
284  //! get a named value with type int, with default
285  CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
286  {return GetValueWithDefault(name, defaultValue);}
287 
288  //! used by derived classes to check for type mismatch
289  CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
290  {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
291 
292  template <class T>
293  void GetRequiredParameter(const char *className, const char *name, T &value) const
294  {
295  if (!GetValue(name, value))
296  throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
297  }
298 
299  CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
300  {
301  if (!GetIntValue(name, value))
302  throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
303  }
304 
305  //! to be implemented by derived classes, users should use one of the above functions instead
306  CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
307 };
308 
309 //! namespace containing value name definitions
310 /*! value names, types and semantics:
311 
312  ThisObject:ClassName (ClassName, copy of this object or a subobject)
313  ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
314 */
315 DOCUMENTED_NAMESPACE_BEGIN(Name)
316 // more names defined in argnames.h
317 DOCUMENTED_NAMESPACE_END
318 
319 //! empty set of name-value pairs
320 extern CRYPTOPP_DLL const NameValuePairs &g_nullNameValuePairs;
321 
322 // ********************************************************
323 
324 //! interface for cloning objects, this is not implemented by most classes yet
325 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
326 {
327 public:
328  virtual ~Clonable() {}
329  //! this is not implemented by most classes yet
330  virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
331 };
332 
333 //! interface for all crypto algorithms
334 
335 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
336 {
337 public:
338  /*! When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
339  this constructor throws SelfTestFailure if the self test hasn't been run or fails. */
340  Algorithm(bool checkSelfTestStatus = true);
341  //! returns name of this algorithm, not universally implemented yet
342  virtual std::string AlgorithmName() const {return "unknown";}
343 };
344 
345 //! keying interface for crypto algorithms that take byte strings as keys
346 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
347 {
348 public:
349  virtual ~SimpleKeyingInterface() {}
350 
351  //! returns smallest valid key length in bytes */
352  virtual size_t MinKeyLength() const =0;
353  //! returns largest valid key length in bytes */
354  virtual size_t MaxKeyLength() const =0;
355  //! returns default (recommended) key length in bytes */
356  virtual size_t DefaultKeyLength() const =0;
357 
358  //! returns the smallest valid key length in bytes that is >= min(n, GetMaxKeyLength())
359  virtual size_t GetValidKeyLength(size_t n) const =0;
360 
361  //! returns whether n is a valid key length
362  virtual bool IsValidKeyLength(size_t n) const
363  {return n == GetValidKeyLength(n);}
364 
365  //! set or reset the key of this object
366  /*! \param params is used to specify Rounds, BlockSize, etc. */
367  virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
368 
369  //! calls SetKey() with an NameValuePairs object that just specifies "Rounds"
370  void SetKeyWithRounds(const byte *key, size_t length, int rounds);
371 
372  //! calls SetKey() with an NameValuePairs object that just specifies "IV"
373  void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
374 
375  //! calls SetKey() with an NameValuePairs object that just specifies "IV"
376  void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
377  {SetKeyWithIV(key, length, iv, IVSize());}
378 
379  enum IV_Requirement {UNIQUE_IV = 0, RANDOM_IV, UNPREDICTABLE_RANDOM_IV, INTERNALLY_GENERATED_IV, NOT_RESYNCHRONIZABLE};
380  //! returns the minimal requirement for secure IVs
381  virtual IV_Requirement IVRequirement() const =0;
382 
383  //! returns whether this object can be resynchronized (i.e. supports initialization vectors)
384  /*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */
385  bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
386  //! returns whether this object can use random IVs (in addition to ones returned by GetNextIV)
387  bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
388  //! returns whether this object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV)
389  bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
390  //! returns whether this object can use structured IVs, for example a counter (in addition to ones returned by GetNextIV)
391  bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
392 
393  virtual unsigned int IVSize() const {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
394  //! returns default length of IVs accepted by this object
395  unsigned int DefaultIVLength() const {return IVSize();}
396  //! returns minimal length of IVs accepted by this object
397  virtual unsigned int MinIVLength() const {return IVSize();}
398  //! returns maximal length of IVs accepted by this object
399  virtual unsigned int MaxIVLength() const {return IVSize();}
400  //! resynchronize with an IV. ivLength=-1 means use IVSize()
401  virtual void Resynchronize(const byte *iv, int ivLength=-1) {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
402  //! get a secure IV for the next message
403  /*! This method should be called after you finish encrypting one message and are ready to start the next one.
404  After calling it, you must call SetKey() or Resynchronize() before using this object again.
405  This method is not implemented on decryption objects. */
406  virtual void GetNextIV(RandomNumberGenerator &rng, byte *IV);
407 
408 protected:
409  virtual const Algorithm & GetAlgorithm() const =0;
410  virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
411 
412  void ThrowIfInvalidKeyLength(size_t length);
413  void ThrowIfResynchronizable(); // to be called when no IV is passed
414  void ThrowIfInvalidIV(const byte *iv); // check for NULL IV if it can't be used
415  size_t ThrowIfInvalidIVLength(int size);
416  const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
417  inline void AssertValidKeyLength(size_t length) const
418  {assert(IsValidKeyLength(length));}
419 };
420 
421 //! interface for the data processing part of block ciphers
422 
423 /*! Classes derived from BlockTransformation are block ciphers
424  in ECB mode (for example the DES::Encryption class), which are stateless.
425  These classes should not be used directly, but only in combination with
426  a mode class (see CipherModeDocumentation in modes.h).
427 */
428 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
429 {
430 public:
431  //! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock
432  virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
433 
434  //! encrypt or decrypt one block
435  /*! \pre size of inBlock and outBlock == BlockSize() */
436  void ProcessBlock(const byte *inBlock, byte *outBlock) const
437  {ProcessAndXorBlock(inBlock, NULL, outBlock);}
438 
439  //! encrypt or decrypt one block in place
440  void ProcessBlock(byte *inoutBlock) const
441  {ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);}
442 
443  //! block size of the cipher in bytes
444  virtual unsigned int BlockSize() const =0;
445 
446  //! returns how inputs and outputs should be aligned for optimal performance
447  virtual unsigned int OptimalDataAlignment() const;
448 
449  //! returns true if this is a permutation (i.e. there is an inverse transformation)
450  virtual bool IsPermutation() const {return true;}
451 
452  //! returns true if this is an encryption object
453  virtual bool IsForwardTransformation() const =0;
454 
455  //! return number of blocks that can be processed in parallel, for bit-slicing implementations
456  virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
457 
458  enum {BT_InBlockIsCounter=1, BT_DontIncrementInOutPointers=2, BT_XorInput=4, BT_ReverseDirection=8, BT_AllowParallel=16} FlagsForAdvancedProcessBlocks;
459 
460  //! encrypt and xor blocks according to flags (see FlagsForAdvancedProcessBlocks)
461  /*! /note If BT_InBlockIsCounter is set, last byte of inBlocks may be modified. */
462  virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
463 
464  inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
465 };
466 
467 //! interface for the data processing part of stream ciphers
468 
469 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
470 {
471 public:
472  //! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
473  StreamTransformation& Ref() {return *this;}
474 
475  //! returns block size, if input must be processed in blocks, otherwise 1
476  virtual unsigned int MandatoryBlockSize() const {return 1;}
477 
478  //! returns the input block size that is most efficient for this cipher
479  /*! \note optimal input length is n * OptimalBlockSize() - GetOptimalBlockSizeUsed() for any n > 0 */
480  virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
481  //! returns how much of the current block is used up
482  virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
483 
484  //! returns how input should be aligned for optimal performance
485  virtual unsigned int OptimalDataAlignment() const;
486 
487  //! encrypt or decrypt an array of bytes of specified length
488  /*! \note either inString == outString, or they don't overlap */
489  virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
490 
491  //! for ciphers where the last block of data is special, encrypt or decrypt the last block of data
492  /*! For now the only use of this function is for CBC-CTS mode. */
493  virtual void ProcessLastBlock(byte *outString, const byte *inString, size_t length);
494  //! returns the minimum size of the last block, 0 indicating the last block is not special
495  virtual unsigned int MinLastBlockSize() const {return 0;}
496 
497  //! same as ProcessData(inoutString, inoutString, length)
498  inline void ProcessString(byte *inoutString, size_t length)
499  {ProcessData(inoutString, inoutString, length);}
500  //! same as ProcessData(outString, inString, length)
501  inline void ProcessString(byte *outString, const byte *inString, size_t length)
502  {ProcessData(outString, inString, length);}
503  //! implemented as {ProcessData(&input, &input, 1); return input;}
504  inline byte ProcessByte(byte input)
505  {ProcessData(&input, &input, 1); return input;}
506 
507  //! returns whether this cipher supports random access
508  virtual bool IsRandomAccess() const =0;
509  //! for random access ciphers, seek to an absolute position
510  virtual void Seek(lword n)
511  {
512  assert(!IsRandomAccess());
513  throw NotImplemented("StreamTransformation: this object doesn't support random access");
514  }
515 
516  //! returns whether this transformation is self-inverting (e.g. xor with a keystream)
517  virtual bool IsSelfInverting() const =0;
518  //! returns whether this is an encryption object
519  virtual bool IsForwardTransformation() const =0;
520 };
521 
522 //! interface for hash functions and data processing part of MACs
523 
524 /*! HashTransformation objects are stateful. They are created in an initial state,
525  change state as Update() is called, and return to the initial
526  state when Final() is called. This interface allows a large message to
527  be hashed in pieces by calling Update() on each piece followed by
528  calling Final().
529 */
530 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
531 {
532 public:
533  //! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
534  HashTransformation& Ref() {return *this;}
535 
536  //! process more input
537  virtual void Update(const byte *input, size_t length) =0;
538 
539  //! request space to write input into
540  virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULL;}
541 
542  //! compute hash for current message, then restart for a new message
543  /*! \pre size of digest == DigestSize(). */
544  virtual void Final(byte *digest)
545  {TruncatedFinal(digest, DigestSize());}
546 
547  //! discard the current state, and restart with a new message
548  virtual void Restart()
549  {TruncatedFinal(NULL, 0);}
550 
551  //! size of the hash/digest/MAC returned by Final()
552  virtual unsigned int DigestSize() const =0;
553 
554  //! same as DigestSize()
555  unsigned int TagSize() const {return DigestSize();}
556 
557 
558  //! block size of underlying compression function, or 0 if not block based
559  virtual unsigned int BlockSize() const {return 0;}
560 
561  //! input to Update() should have length a multiple of this for optimal speed
562  virtual unsigned int OptimalBlockSize() const {return 1;}
563 
564  //! returns how input should be aligned for optimal performance
565  virtual unsigned int OptimalDataAlignment() const;
566 
567  //! use this if your input is in one piece and you don't want to call Update() and Final() separately
568  virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
569  {Update(input, length); Final(digest);}
570 
571  //! verify that digest is a valid digest for the current message, then reinitialize the object
572  /*! Default implementation is to call Final() and do a bitwise comparison
573  between its output and digest. */
574  virtual bool Verify(const byte *digest)
575  {return TruncatedVerify(digest, DigestSize());}
576 
577  //! use this if your input is in one piece and you don't want to call Update() and Verify() separately
578  virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
579  {Update(input, length); return Verify(digest);}
580 
581  //! truncated version of Final()
582  virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
583 
584  //! truncated version of CalculateDigest()
585  virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
586  {Update(input, length); TruncatedFinal(digest, digestSize);}
587 
588  //! truncated version of Verify()
589  virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
590 
591  //! truncated version of VerifyDigest()
592  virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
593  {Update(input, length); return TruncatedVerify(digest, digestLength);}
594 
595 protected:
596  void ThrowIfInvalidTruncatedSize(size_t size) const;
597 };
598 
600 
601 //! interface for one direction (encryption or decryption) of a block cipher
602 /*! \note These objects usually should not be used directly. See BlockTransformation for more details. */
603 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
604 {
605 protected:
606  const Algorithm & GetAlgorithm() const {return *this;}
607 };
608 
609 //! interface for one direction (encryption or decryption) of a stream cipher or cipher mode
610 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
611 {
612 protected:
613  const Algorithm & GetAlgorithm() const {return *this;}
614 };
615 
616 //! interface for message authentication codes
617 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
618 {
619 protected:
620  const Algorithm & GetAlgorithm() const {return *this;}
621 };
622 
623 //! interface for for one direction (encryption or decryption) of a stream cipher or block cipher mode with authentication
624 /*! The StreamTransformation part of this interface is used to encrypt/decrypt the data, and the MessageAuthenticationCode part of this
625  interface is used to input additional authenticated data (AAD, which is MAC'ed but not encrypted), and to generate/verify the MAC. */
626 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
627 {
628 public:
629  //! this indicates that a member function was called in the wrong state, for example trying to encrypt a message before having set the key or IV
630  class BadState : public Exception
631  {
632  public:
633  explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
634  explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
635  };
636 
637  //! the maximum length of AAD that can be input before the encrypted data
638  virtual lword MaxHeaderLength() const =0;
639  //! the maximum length of encrypted data
640  virtual lword MaxMessageLength() const =0;
641  //! the maximum length of AAD that can be input after the encrypted data
642  virtual lword MaxFooterLength() const {return 0;}
643  //! if this function returns true, SpecifyDataLengths() must be called before attempting to input data
644  /*! This is the case for some schemes, such as CCM. */
645  virtual bool NeedsPrespecifiedDataLengths() const {return false;}
646  //! this function only needs to be called if NeedsPrespecifiedDataLengths() returns true
647  void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
648  //! encrypt and generate MAC in one call. will truncate MAC if macSize < TagSize()
649  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);
650  //! decrypt and verify MAC in one call, returning true iff MAC is valid. will assume MAC is truncated if macLength < TagSize()
651  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);
652 
653  // redeclare this to avoid compiler ambiguity errors
654  virtual std::string AlgorithmName() const =0;
655 
656 protected:
657  const Algorithm & GetAlgorithm() const {return *static_cast<const MessageAuthenticationCode *>(this);}
658  virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength) {}
659 };
660 
661 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
662 typedef SymmetricCipher StreamCipher;
663 #endif
664 
665 //! interface for random number generators
666 /*! All return values are uniformly distributed over the range specified.
667 */
668 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
669 {
670 public:
671  //! update RNG state with additional unpredictable values
672  virtual void IncorporateEntropy(const byte *input, size_t length) {throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");}
673 
674  //! returns true if IncorporateEntropy is implemented
675  virtual bool CanIncorporateEntropy() const {return false;}
676 
677  //! generate new random byte and return it
678  virtual byte GenerateByte();
679 
680  //! generate new random bit and return it
681  /*! Default implementation is to call GenerateByte() and return its lowest bit. */
682  virtual unsigned int GenerateBit();
683 
684  //! generate a random 32 bit word in the range min to max, inclusive
685  virtual word32 GenerateWord32(word32 a=0, word32 b=0xffffffffL);
686 
687  //! generate random array of bytes
688  virtual void GenerateBlock(byte *output, size_t size);
689 
690  //! generate and discard n bytes
691  virtual void DiscardBytes(size_t n);
692 
693  //! generate random bytes as input to a BufferedTransformation
694  virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
695 
696  //! randomly shuffle the specified array, resulting permutation is uniformly distributed
697  template <class IT> void Shuffle(IT begin, IT end)
698  {
699  for (; begin != end; ++begin)
700  std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1));
701  }
702 
703 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
704  byte GetByte() {return GenerateByte();}
705  unsigned int GetBit() {return GenerateBit();}
706  word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);}
707  word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);}
708  void GetBlock(byte *output, size_t size) {GenerateBlock(output, size);}
709 #endif
710 };
711 
712 //! returns a reference that can be passed to functions that ask for a RNG but doesn't actually use it
713 CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
714 
715 class WaitObjectContainer;
716 class CallStack;
717 
718 //! interface for objects that you can wait for
719 
720 class CRYPTOPP_NO_VTABLE Waitable
721 {
722 public:
723  virtual ~Waitable() {}
724 
725  //! maximum number of wait objects that this object can return
726  virtual unsigned int GetMaxWaitObjectCount() const =0;
727  //! put wait objects into container
728  /*! \param callStack is used for tracing no wait loops, example:
729  something.GetWaitObjects(c, CallStack("my func after X", 0));
730  - or in an outer GetWaitObjects() method that itself takes a callStack parameter:
731  innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack)); */
732  virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
733  //! wait on this object
734  /*! same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container */
735  bool Wait(unsigned long milliseconds, CallStack const& callStack);
736 };
737 
738 //! the default channel for BufferedTransformation, equal to the empty string
739 extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
740 
741 //! channel for additional authenticated data, equal to "AAD"
742 extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
743 
744 //! interface for buffered transformations
745 
746 /*! BufferedTransformation is a generalization of BlockTransformation,
747  StreamTransformation, and HashTransformation.
748 
749  A buffered transformation is an object that takes a stream of bytes
750  as input (this may be done in stages), does some computation on them, and
751  then places the result into an internal buffer for later retrieval. Any
752  partial result already in the output buffer is not modified by further
753  input.
754 
755  If a method takes a "blocking" parameter, and you
756  pass "false" for it, the method will return before all input has been processed if
757  the input cannot be processed without waiting (for network buffers to become available, for example).
758  In this case the method will return true
759  or a non-zero integer value. When this happens you must continue to call the method with the same
760  parameters until it returns false or zero, before calling any other method on it or
761  attached BufferedTransformation. The integer return value in this case is approximately
762  the number of bytes left to be processed, and can be used to implement a progress bar.
763 
764  For functions that take a "propagation" parameter, propagation != 0 means pass on the signal to attached
765  BufferedTransformation objects, with propagation decremented at each step until it reaches 0.
766  -1 means unlimited propagation.
767 
768  \nosubgrouping
769 */
770 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
771 {
772 public:
773  // placed up here for CW8
774  static const std::string &NULL_CHANNEL; // same as DEFAULT_CHANNEL, for backwards compatibility
775 
776  BufferedTransformation() : Algorithm(false) {}
777 
778  //! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
779  BufferedTransformation& Ref() {return *this;}
780 
781  //! \name INPUT
782  //@{
783  //! input a byte for processing
784  size_t Put(byte inByte, bool blocking=true)
785  {return Put(&inByte, 1, blocking);}
786  //! input multiple bytes
787  size_t Put(const byte *inString, size_t length, bool blocking=true)
788  {return Put2(inString, length, 0, blocking);}
789 
790  //! input a 16-bit word
791  size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
792  //! input a 32-bit word
793  size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
794 
795  //! request space which can be written into by the caller, and then used as input to Put()
796  /*! \param size is requested size (as a hint) for input, and size of the returned space for output */
797  /*! \note The purpose of this method is to help avoid doing extra memory allocations. */
798  virtual byte * CreatePutSpace(size_t &size) {size=0; return NULL;}
799 
800  virtual bool CanModifyInput() const {return false;}
801 
802  //! input multiple bytes that may be modified by callee
803  size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
804  {return PutModifiable2(inString, length, 0, blocking);}
805 
806  bool MessageEnd(int propagation=-1, bool blocking=true)
807  {return !!Put2(NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
808  size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
809  {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
810 
811  //! input multiple bytes for blocking or non-blocking processing
812  /*! \param messageEnd means how many filters to signal MessageEnd to, including this one */
813  virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
814  //! input multiple bytes that may be modified by callee for blocking or non-blocking processing
815  /*! \param messageEnd means how many filters to signal MessageEnd to, including this one */
816  virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
817  {return Put2(inString, length, messageEnd, blocking);}
818 
819  //! thrown by objects that have not implemented nonblocking input processing
821  {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
822  //@}
823 
824  //! \name WAITING
825  //@{
826  unsigned int GetMaxWaitObjectCount() const;
827  void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
828  //@}
829 
830  //! \name SIGNALS
831  //@{
832  virtual void IsolatedInitialize(const NameValuePairs &parameters) {throw NotImplemented("BufferedTransformation: this object can't be reinitialized");}
833  virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
834  virtual bool IsolatedMessageSeriesEnd(bool blocking) {return false;}
835 
836  //! initialize or reinitialize this object
837  virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
838  //! flush buffered input and/or output
839  /*! \param hardFlush is used to indicate whether all data should be flushed
840  \note Hard flushes must be used with care. It means try to process and output everything, even if
841  there may not be enough data to complete the action. For example, hard flushing a HexDecoder would
842  cause an error if you do it after inputing an odd number of hex encoded characters.
843  For some types of filters, for example ZlibDecompressor, hard flushes can only
844  be done at "synchronization points". These synchronization points are positions in the data
845  stream that are created by hard flushes on the corresponding reverse filters, in this
846  example ZlibCompressor. This is useful when zlib compressed data is moved across a
847  network in packets and compression state is preserved across packets, as in the ssh2 protocol.
848  */
849  virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
850  //! mark end of a series of messages
851  /*! There should be a MessageEnd immediately before MessageSeriesEnd. */
852  virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
853 
854  //! set propagation of automatically generated and transferred signals
855  /*! propagation == 0 means do not automaticly generate signals */
856  virtual void SetAutoSignalPropagation(int propagation) {}
857 
858  //!
859  virtual int GetAutoSignalPropagation() const {return 0;}
860 public:
861 
862 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
863  void Close() {MessageEnd();}
864 #endif
865  //@}
866 
867  //! \name RETRIEVAL OF ONE MESSAGE
868  //@{
869  //! returns number of bytes that is currently ready for retrieval
870  /*! All retrieval functions return the actual number of bytes
871  retrieved, which is the lesser of the request number and
872  MaxRetrievable(). */
873  virtual lword MaxRetrievable() const;
874 
875  //! returns whether any bytes are currently ready for retrieval
876  virtual bool AnyRetrievable() const;
877 
878  //! try to retrieve a single byte
879  virtual size_t Get(byte &outByte);
880  //! try to retrieve multiple bytes
881  virtual size_t Get(byte *outString, size_t getMax);
882 
883  //! peek at the next byte without removing it from the output buffer
884  virtual size_t Peek(byte &outByte) const;
885  //! peek at multiple bytes without removing them from the output buffer
886  virtual size_t Peek(byte *outString, size_t peekMax) const;
887 
888  //! try to retrieve a 16-bit word
889  size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
890  //! try to retrieve a 32-bit word
891  size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
892 
893  //! try to peek at a 16-bit word
894  size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
895  //! try to peek at a 32-bit word
896  size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
897 
898  //! move transferMax bytes of the buffered output to target as input
899  lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
900  {TransferTo2(target, transferMax, channel); return transferMax;}
901 
902  //! discard skipMax bytes from the output buffer
903  virtual lword Skip(lword skipMax=LWORD_MAX);
904 
905  //! copy copyMax bytes of the buffered output to target as input
906  lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
907  {return CopyRangeTo(target, 0, copyMax, channel);}
908 
909  //! copy copyMax bytes of the buffered output, starting at position (relative to current position), to target as input
910  lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
911  {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
912 
913 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
914  unsigned long MaxRetrieveable() const {return MaxRetrievable();}
915 #endif
916  //@}
917 
918  //! \name RETRIEVAL OF MULTIPLE MESSAGES
919  //@{
920  //!
921  virtual lword TotalBytesRetrievable() const;
922  //! number of times MessageEnd() has been received minus messages retrieved or skipped
923  virtual unsigned int NumberOfMessages() const;
924  //! returns true if NumberOfMessages() > 0
925  virtual bool AnyMessages() const;
926  //! start retrieving the next message
927  /*!
928  Returns false if no more messages exist or this message
929  is not completely retrieved.
930  */
931  virtual bool GetNextMessage();
932  //! skip count number of messages
933  virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
934  //!
935  unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
936  {TransferMessagesTo2(target, count, channel); return count;}
937  //!
938  unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
939 
940  //!
941  virtual void SkipAll();
942  //!
943  void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
944  {TransferAllTo2(target, channel);}
945  //!
946  void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
947 
948  virtual bool GetNextMessageSeries() {return false;}
949  virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
950  virtual unsigned int NumberOfMessageSeries() const {return 0;}
951  //@}
952 
953  //! \name NON-BLOCKING TRANSFER OF OUTPUT
954  //@{
955  //! upon return, byteCount contains number of bytes that have finished being transfered, and returns the number of bytes left in the current transfer block
956  virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
957  //! upon return, begin contains the start position of data yet to be finished copying, and returns the number of bytes left in the current transfer block
958  virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
959  //! upon return, messageCount contains number of messages that have finished being transfered, and returns the number of bytes left in the current transfer block
960  size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
961  //! returns the number of bytes left in the current transfer block
962  size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
963  //@}
964 
965  //! \name CHANNELS
966  //@{
968  {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
970  {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
971 
972  size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
973  {return ChannelPut(channel, &inByte, 1, blocking);}
974  size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
975  {return ChannelPut2(channel, inString, length, 0, blocking);}
976 
977  size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
978  {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
979 
980  size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
981  size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
982 
983  bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
984  {return !!ChannelPut2(channel, NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
985  size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
986  {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
987 
988  virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
989 
990  virtual size_t ChannelPut2(const std::string &channel, const byte *begin, size_t length, int messageEnd, bool blocking);
991  virtual size_t ChannelPutModifiable2(const std::string &channel, byte *begin, size_t length, int messageEnd, bool blocking);
992 
993  virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
994  virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
995 
996  virtual void SetRetrievalChannel(const std::string &channel);
997  //@}
998 
999  //! \name ATTACHMENT
1000  /*! Some BufferedTransformation objects (e.g. Filter objects)
1001  allow other BufferedTransformation objects to be attached. When
1002  this is done, the first object instead of buffering its output,
1003  sents that output to the attached object as input. The entire
1004  attachment chain is deleted when the anchor object is destructed.
1005  */
1006  //@{
1007  //! returns whether this object allows attachment
1008  virtual bool Attachable() {return false;}
1009  //! returns the object immediately attached to this object or NULL for no attachment
1010  virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;}
1011  //!
1012  virtual const BufferedTransformation *AttachedTransformation() const
1013  {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
1014  //! delete the current attachment chain and replace it with newAttachment
1015  virtual void Detach(BufferedTransformation *newAttachment = 0)
1016  {assert(!Attachable()); throw NotImplemented("BufferedTransformation: this object is not attachable");}
1017  //! add newAttachment to the end of attachment chain
1018  virtual void Attach(BufferedTransformation *newAttachment);
1019  //@}
1020 
1021 protected:
1022  static int DecrementPropagation(int propagation)
1023  {return propagation != 0 ? propagation - 1 : 0;}
1024 
1025 private:
1026  byte m_buf[4]; // for ChannelPutWord16 and ChannelPutWord32, to ensure buffer isn't deallocated before non-blocking operation completes
1027 };
1028 
1029 //! returns a reference to a BufferedTransformation object that discards all input
1031 
1032 //! interface for crypto material, such as public and private keys, and crypto parameters
1033 
1034 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
1035 {
1036 public:
1037  //! exception thrown when invalid crypto material is detected
1038  class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
1039  {
1040  public:
1041  explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
1042  };
1043 
1044  //! assign values from source to this object
1045  /*! \note This function can be used to create a public key from a private key. */
1046  virtual void AssignFrom(const NameValuePairs &source) =0;
1047 
1048  //! check this object for errors
1049  /*! \param level denotes the level of thoroughness:
1050  0 - using this object won't cause a crash or exception (rng is ignored)
1051  1 - this object will probably function (encrypt, sign, etc.) correctly (but may not check for weak keys and such)
1052  2 - make sure this object will function correctly, and do reasonable security checks
1053  3 - do checks that may take a long time
1054  \return true if the tests pass */
1055  virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
1056 
1057  //! throws InvalidMaterial if this object fails Validate() test
1058  virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
1059  {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
1060 
1061 // virtual std::vector<std::string> GetSupportedFormats(bool includeSaveOnly=false, bool includeLoadOnly=false);
1062 
1063  //! save key into a BufferedTransformation
1064  virtual void Save(BufferedTransformation &bt) const
1065  {throw NotImplemented("CryptoMaterial: this object does not support saving");}
1066 
1067  //! load key from a BufferedTransformation
1068  /*! \throws KeyingErr if decode fails
1069  \note Generally does not check that the key is valid.
1070  Call ValidateKey() or ThrowIfInvalidKey() to check that. */
1071  virtual void Load(BufferedTransformation &bt)
1072  {throw NotImplemented("CryptoMaterial: this object does not support loading");}
1073 
1074  //! \return whether this object supports precomputation
1075  virtual bool SupportsPrecomputation() const {return false;}
1076  //! do precomputation
1077  /*! The exact semantics of Precompute() is varies, but
1078  typically it means calculate a table of n objects
1079  that can be used later to speed up computation. */
1080  virtual void Precompute(unsigned int n)
1081  {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
1082  //! retrieve previously saved precomputation
1083  virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
1084  {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
1085  //! save precomputation for later use
1086  virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
1087  {assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
1088 
1089  // for internal library use
1090  void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
1091 
1092 #if (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
1093  // Sun Studio 11/CC 5.8 workaround: it generates incorrect code when casting to an empty virtual base class
1094  char m_sunCCworkaround;
1095 #endif
1096 };
1097 
1098 //! interface for generatable crypto material, such as private keys and crypto parameters
1099 
1100 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
1101 {
1102 public:
1103  //! generate a random key or crypto parameters
1104  /*! \throws KeyingErr if algorithm parameters are invalid, or if a key can't be generated
1105  (e.g., if this is a public key object) */
1107  {throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");}
1108 
1109  //! calls the above function with a NameValuePairs object that just specifies "KeySize"
1110  void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
1111 };
1112 
1113 //! interface for public keys
1114 
1115 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
1116 {
1117 };
1118 
1119 //! interface for private keys
1120 
1121 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
1122 {
1123 };
1124 
1125 //! interface for crypto prameters
1126 
1127 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
1128 {
1129 };
1130 
1131 //! interface for asymmetric algorithms
1132 
1133 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
1134 {
1135 public:
1136  //! returns a reference to the crypto material used by this object
1137  virtual CryptoMaterial & AccessMaterial() =0;
1138  //! returns a const reference to the crypto material used by this object
1139  virtual const CryptoMaterial & GetMaterial() const =0;
1140 
1141  //! for backwards compatibility, calls AccessMaterial().Load(bt)
1143  {AccessMaterial().Load(bt);}
1144  //! for backwards compatibility, calls GetMaterial().Save(bt)
1146  {GetMaterial().Save(bt);}
1147 };
1148 
1149 //! interface for asymmetric algorithms using public keys
1150 
1151 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
1152 {
1153 public:
1154  // VC60 workaround: no co-variant return type
1155  CryptoMaterial & AccessMaterial() {return AccessPublicKey();}
1156  const CryptoMaterial & GetMaterial() const {return GetPublicKey();}
1157 
1158  virtual PublicKey & AccessPublicKey() =0;
1159  virtual const PublicKey & GetPublicKey() const {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
1160 };
1161 
1162 //! interface for asymmetric algorithms using private keys
1163 
1164 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
1165 {
1166 public:
1167  CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
1168  const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
1169 
1170  virtual PrivateKey & AccessPrivateKey() =0;
1171  virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
1172 };
1173 
1174 //! interface for key agreement algorithms
1175 
1176 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
1177 {
1178 public:
1179  CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
1180  const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
1181 
1182  virtual CryptoParameters & AccessCryptoParameters() =0;
1183  virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
1184 };
1185 
1186 //! interface for public-key encryptors and decryptors
1187 
1188 /*! This class provides an interface common to encryptors and decryptors
1189  for querying their plaintext and ciphertext lengths.
1190 */
1191 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
1192 {
1193 public:
1194  virtual ~PK_CryptoSystem() {}
1195 
1196  //! maximum length of plaintext for a given ciphertext length
1197  /*! \note This function returns 0 if ciphertextLength is not valid (too long or too short). */
1198  virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
1199 
1200  //! calculate length of ciphertext given length of plaintext
1201  /*! \note This function returns 0 if plaintextLength is not valid (too long). */
1202  virtual size_t CiphertextLength(size_t plaintextLength) const =0;
1203 
1204  //! this object supports the use of the parameter with the given name
1205  /*! some possible parameter names: EncodingParameters, KeyDerivationParameters */
1206  virtual bool ParameterSupported(const char *name) const =0;
1207 
1208  //! return fixed ciphertext length, if one exists, otherwise return 0
1209  /*! \note "Fixed" here means length of ciphertext does not depend on length of plaintext.
1210  It usually does depend on the key length. */
1211  virtual size_t FixedCiphertextLength() const {return 0;}
1212 
1213  //! return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0
1214  virtual size_t FixedMaxPlaintextLength() const {return 0;}
1215 
1216 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
1217  size_t MaxPlainTextLength(size_t cipherTextLength) const {return MaxPlaintextLength(cipherTextLength);}
1218  size_t CipherTextLength(size_t plainTextLength) const {return CiphertextLength(plainTextLength);}
1219 #endif
1220 };
1221 
1222 //! interface for public-key encryptors
1223 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
1224 {
1225 public:
1226  //! exception thrown when trying to encrypt plaintext of invalid length
1227  class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
1228  {
1229  public:
1230  InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
1231  };
1232 
1233  //! encrypt a byte string
1234  /*! \pre CiphertextLength(plaintextLength) != 0 (i.e., plaintext isn't too long)
1235  \pre size of ciphertext == CiphertextLength(plaintextLength)
1236  */
1237  virtual void Encrypt(RandomNumberGenerator &rng,
1238  const byte *plaintext, size_t plaintextLength,
1239  byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
1240 
1241  //! create a new encryption filter
1242  /*! \note The caller is responsible for deleting the returned pointer.
1243  \note Encoding parameters should be passed in the "EP" channel.
1244  */
1245  virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
1246  BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
1247 };
1248 
1249 //! interface for public-key decryptors
1250 
1251 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
1252 {
1253 public:
1254  //! decrypt a byte string, and return the length of plaintext
1255  /*! \pre size of plaintext == MaxPlaintextLength(ciphertextLength) bytes.
1256  \return the actual length of the plaintext, indication that decryption failed.
1257  */
1258  virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
1259  const byte *ciphertext, size_t ciphertextLength,
1260  byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
1261 
1262  //! create a new decryption filter
1263  /*! \note caller is responsible for deleting the returned pointer
1264  */
1265  virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
1266  BufferedTransformation *attachment=NULL, const NameValuePairs &parameters = g_nullNameValuePairs) const;
1267 
1268  //! decrypt a fixed size ciphertext
1269  DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
1270  {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
1271 };
1272 
1273 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
1274 typedef PK_CryptoSystem PK_FixedLengthCryptoSystem;
1275 typedef PK_Encryptor PK_FixedLengthEncryptor;
1276 typedef PK_Decryptor PK_FixedLengthDecryptor;
1277 #endif
1278 
1279 //! interface for public-key signers and verifiers
1280 
1281 /*! This class provides an interface common to signers and verifiers
1282  for querying scheme properties.
1283 */
1284 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
1285 {
1286 public:
1287  //! invalid key exception, may be thrown by any function in this class if the private or public key has a length that can't be used
1288  class CRYPTOPP_DLL InvalidKeyLength : public Exception
1289  {
1290  public:
1291  InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
1292  };
1293 
1294  //! key too short exception, may be thrown by any function in this class if the private or public key is too short to sign or verify anything
1295  class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
1296  {
1297  public:
1298  KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
1299  };
1300 
1301  virtual ~PK_SignatureScheme() {}
1302 
1303  //! signature length if it only depends on the key, otherwise 0
1304  virtual size_t SignatureLength() const =0;
1305 
1306  //! maximum signature length produced for a given length of recoverable message part
1307  virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const {return SignatureLength();}
1308 
1309  //! length of longest message that can be recovered, or 0 if this signature scheme does not support message recovery
1310  virtual size_t MaxRecoverableLength() const =0;
1311 
1312  //! length of longest message that can be recovered from a signature of given length, or 0 if this signature scheme does not support message recovery
1313  virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
1314 
1315  //! requires a random number generator to sign
1316  /*! if this returns false, NullRNG() can be passed to functions that take RandomNumberGenerator & */
1317  virtual bool IsProbabilistic() const =0;
1318 
1319  //! whether or not a non-recoverable message part can be signed
1320  virtual bool AllowNonrecoverablePart() const =0;
1321 
1322  //! if this function returns true, during verification you must input the signature before the message, otherwise you can input it at anytime */
1323  virtual bool SignatureUpfront() const {return false;}
1324 
1325  //! whether you must input the recoverable part before the non-recoverable part during signing
1326  virtual bool RecoverablePartFirst() const =0;
1327 };
1328 
1329 //! interface for accumulating messages to be signed or verified
1330 /*! Only Update() should be called
1331  on this class. No other functions inherited from HashTransformation should be called.
1332 */
1333 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
1334 {
1335 public:
1336  //! should not be called on PK_MessageAccumulator
1337  unsigned int DigestSize() const
1338  {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
1339  //! should not be called on PK_MessageAccumulator
1340  void TruncatedFinal(byte *digest, size_t digestSize)
1341  {throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");}
1342 };
1343 
1344 //! interface for public-key signers
1345 
1346 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
1347 {
1348 public:
1349  //! create a new HashTransformation to accumulate the message to be signed
1350  virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
1351 
1352  virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
1353 
1354  //! sign and delete messageAccumulator (even in case of exception thrown)
1355  /*! \pre size of signature == MaxSignatureLength()
1356  \return actual signature length
1357  */
1358  virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
1359 
1360  //! sign and restart messageAccumulator
1361  /*! \pre size of signature == MaxSignatureLength()
1362  \return actual signature length
1363  */
1364  virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
1365 
1366  //! sign a message
1367  /*! \pre size of signature == MaxSignatureLength()
1368  \return actual signature length
1369  */
1370  virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
1371 
1372  //! sign a recoverable message
1373  /*! \pre size of signature == MaxSignatureLength(recoverableMessageLength)
1374  \return actual signature length
1375  */
1376  virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
1377  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
1378 };
1379 
1380 //! interface for public-key signature verifiers
1381 /*! The Recover* functions throw NotImplemented if the signature scheme does not support
1382  message recovery.
1383  The Verify* functions throw InvalidDataFormat if the scheme does support message
1384  recovery and the signature contains a non-empty recoverable message part. The
1385  Recovery* functions should be used in that case.
1386 */
1387 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
1388 {
1389 public:
1390  //! create a new HashTransformation to accumulate the message to be verified
1391  virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
1392 
1393  //! input signature into a message accumulator
1394  virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
1395 
1396  //! check whether messageAccumulator contains a valid signature and message, and delete messageAccumulator (even in case of exception thrown)
1397  virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
1398 
1399  //! check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
1400  virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
1401 
1402  //! check whether input signature is a valid signature for input message
1403  virtual bool VerifyMessage(const byte *message, size_t messageLen,
1404  const byte *signature, size_t signatureLength) const;
1405 
1406  //! recover a message from its signature
1407  /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
1408  */
1409  virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
1410 
1411  //! recover a message from its signature
1412  /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
1413  */
1414  virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
1415 
1416  //! recover a message from its signature
1417  /*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
1418  */
1419  virtual DecodingResult RecoverMessage(byte *recoveredMessage,
1420  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
1421  const byte *signature, size_t signatureLength) const;
1422 };
1423 
1424 //! interface for domains of simple key agreement protocols
1425 
1426 /*! A key agreement domain is a set of parameters that must be shared
1427  by two parties in a key agreement protocol, along with the algorithms
1428  for generating key pairs and deriving agreed values.
1429 */
1430 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
1431 {
1432 public:
1433  //! return length of agreed value produced
1434  virtual unsigned int AgreedValueLength() const =0;
1435  //! return length of private keys in this domain
1436  virtual unsigned int PrivateKeyLength() const =0;
1437  //! return length of public keys in this domain
1438  virtual unsigned int PublicKeyLength() const =0;
1439  //! generate private key
1440  /*! \pre size of privateKey == PrivateKeyLength() */
1441  virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
1442  //! generate public key
1443  /*! \pre size of publicKey == PublicKeyLength() */
1444  virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
1445  //! generate private/public key pair
1446  /*! \note equivalent to calling GeneratePrivateKey() and then GeneratePublicKey() */
1447  virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
1448  //! derive agreed value from your private key and couterparty's public key, return false in case of failure
1449  /*! \note If you have previously validated the public key, use validateOtherPublicKey=false to save time.
1450  \pre size of agreedValue == AgreedValueLength()
1451  \pre length of privateKey == PrivateKeyLength()
1452  \pre length of otherPublicKey == PublicKeyLength()
1453  */
1454  virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
1455 
1456 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
1457  bool ValidateDomainParameters(RandomNumberGenerator &rng) const
1458  {return GetCryptoParameters().Validate(rng, 2);}
1459 #endif
1460 };
1461 
1462 //! interface for domains of authenticated key agreement protocols
1463 
1464 /*! In an authenticated key agreement protocol, each party has two
1465  key pairs. The long-lived key pair is called the static key pair,
1466  and the short-lived key pair is called the ephemeral key pair.
1467 */
1468 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
1469 {
1470 public:
1471  //! return length of agreed value produced
1472  virtual unsigned int AgreedValueLength() const =0;
1473 
1474  //! return length of static private keys in this domain
1475  virtual unsigned int StaticPrivateKeyLength() const =0;
1476  //! return length of static public keys in this domain
1477  virtual unsigned int StaticPublicKeyLength() const =0;
1478  //! generate static private key
1479  /*! \pre size of privateKey == PrivateStaticKeyLength() */
1480  virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
1481  //! generate static public key
1482  /*! \pre size of publicKey == PublicStaticKeyLength() */
1483  virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
1484  //! generate private/public key pair
1485  /*! \note equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey() */
1486  virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
1487 
1488  //! return length of ephemeral private keys in this domain
1489  virtual unsigned int EphemeralPrivateKeyLength() const =0;
1490  //! return length of ephemeral public keys in this domain
1491  virtual unsigned int EphemeralPublicKeyLength() const =0;
1492  //! generate ephemeral private key
1493  /*! \pre size of privateKey == PrivateEphemeralKeyLength() */
1494  virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
1495  //! generate ephemeral public key
1496  /*! \pre size of publicKey == PublicEphemeralKeyLength() */
1497  virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
1498  //! generate private/public key pair
1499  /*! \note equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() */
1500  virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
1501 
1502  //! derive agreed value from your private keys and couterparty's public keys, return false in case of failure
1503  /*! \note The ephemeral public key will always be validated.
1504  If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time.
1505  \pre size of agreedValue == AgreedValueLength()
1506  \pre length of staticPrivateKey == StaticPrivateKeyLength()
1507  \pre length of ephemeralPrivateKey == EphemeralPrivateKeyLength()
1508  \pre length of staticOtherPublicKey == StaticPublicKeyLength()
1509  \pre length of ephemeralOtherPublicKey == EphemeralPublicKeyLength()
1510  */
1511  virtual bool Agree(byte *agreedValue,
1512  const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
1513  const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
1514  bool validateStaticOtherPublicKey=true) const =0;
1515 
1516 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
1517  bool ValidateDomainParameters(RandomNumberGenerator &rng) const
1518  {return GetCryptoParameters().Validate(rng, 2);}
1519 #endif
1520 };
1521 
1522 // interface for password authenticated key agreement protocols, not implemented yet
1523 #if 0
1524 //! interface for protocol sessions
1525 /*! The methods should be called in the following order:
1526 
1527  InitializeSession(rng, parameters); // or call initialize method in derived class
1528  while (true)
1529  {
1530  if (OutgoingMessageAvailable())
1531  {
1532  length = GetOutgoingMessageLength();
1533  GetOutgoingMessage(message);
1534  ; // send outgoing message
1535  }
1536 
1537  if (LastMessageProcessed())
1538  break;
1539 
1540  ; // receive incoming message
1541  ProcessIncomingMessage(message);
1542  }
1543  ; // call methods in derived class to obtain result of protocol session
1544 */
1545 class ProtocolSession
1546 {
1547 public:
1548  //! exception thrown when an invalid protocol message is processed
1549  class ProtocolError : public Exception
1550  {
1551  public:
1552  ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
1553  };
1554 
1555  //! exception thrown when a function is called unexpectedly
1556  /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
1557  class UnexpectedMethodCall : public Exception
1558  {
1559  public:
1560  UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
1561  };
1562 
1563  ProtocolSession() : m_rng(NULL), m_throwOnProtocolError(true), m_validState(false) {}
1564  virtual ~ProtocolSession() {}
1565 
1566  virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
1567 
1568  bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
1569  void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
1570 
1571  bool HasValidState() const {return m_validState;}
1572 
1573  virtual bool OutgoingMessageAvailable() const =0;
1574  virtual unsigned int GetOutgoingMessageLength() const =0;
1575  virtual void GetOutgoingMessage(byte *message) =0;
1576 
1577  virtual bool LastMessageProcessed() const =0;
1578  virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
1579 
1580 protected:
1581  void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
1582  void CheckAndHandleInvalidState() const;
1583  void SetValidState(bool valid) {m_validState = valid;}
1584 
1585  RandomNumberGenerator *m_rng;
1586 
1587 private:
1588  bool m_throwOnProtocolError, m_validState;
1589 };
1590 
1591 class KeyAgreementSession : public ProtocolSession
1592 {
1593 public:
1594  virtual unsigned int GetAgreedValueLength() const =0;
1595  virtual void GetAgreedValue(byte *agreedValue) const =0;
1596 };
1597 
1598 class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
1599 {
1600 public:
1601  void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
1602  const byte *myId, unsigned int myIdLength,
1603  const byte *counterPartyId, unsigned int counterPartyIdLength,
1604  const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
1605 };
1606 
1607 class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
1608 {
1609 public:
1610  //! return whether the domain parameters stored in this object are valid
1611  virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
1612  {return GetCryptoParameters().Validate(rng, 2);}
1613 
1614  virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
1615  virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
1616 
1617  enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
1618 
1619  virtual bool IsValidRole(unsigned int role) =0;
1620  virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
1621 };
1622 #endif
1623 
1624 //! BER Decode Exception Class, may be thrown during an ASN1 BER decode operation
1625 class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
1626 {
1627 public:
1628  BERDecodeErr() : InvalidArgument("BER decode error") {}
1629  BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
1630 };
1631 
1632 //! interface for encoding and decoding ASN1 objects
1633 class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
1634 {
1635 public:
1636  virtual ~ASN1Object() {}
1637  //! decode this object from a BufferedTransformation, using BER (Basic Encoding Rules)
1638  virtual void BERDecode(BufferedTransformation &bt) =0;
1639  //! encode this object into a BufferedTransformation, using DER (Distinguished Encoding Rules)
1640  virtual void DEREncode(BufferedTransformation &bt) const =0;
1641  //! encode this object into a BufferedTransformation, using BER
1642  /*! this may be useful if DEREncode() would be too inefficient */
1643  virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
1644 };
1645 
1646 #ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
1647 typedef PK_SignatureScheme PK_SignatureSystem;
1648 typedef SimpleKeyAgreementDomain PK_SimpleKeyAgreementDomain;
1649 typedef AuthenticatedKeyAgreementDomain PK_AuthenticatedKeyAgreementDomain;
1650 #endif
1651 
1652 NAMESPACE_END
1653 
1654 #endif
base class for all exceptions thrown by Crypto++
Definition: cryptlib.h:109
exception thrown when invalid crypto material is detected
Definition: cryptlib.h:1038
exception thrown when an invalid argument is detected
Definition: cryptlib.h:144
void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
calls SetKey() with an NameValuePairs object that just specifies "IV"
Definition: cryptlib.h:376
bool GetThisObject(T &object) const
get a copy of this object or a subobject of it
Definition: cryptlib.h:247
bool CanUseRandomIVs() const
returns whether this object can use random IVs (in addition to ones returned by GetNextIV) ...
Definition: cryptlib.h:387
interface for message authentication codes
Definition: cryptlib.h:617
ErrorType
error types
Definition: cryptlib.h:113
container of wait objects
Definition: wait.h:146
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
save precomputation for later use
Definition: cryptlib.h:1086
interface for asymmetric algorithms
Definition: cryptlib.h:1133
interface for public-key encryptors and decryptors
Definition: cryptlib.h:1191
error reported by the operating system
Definition: cryptlib.h:179
interface for for one direction (encryption or decryption) of a stream cipher or block cipher mode wi...
Definition: cryptlib.h:626
T GetValueWithDefault(const char *name, T defaultValue) const
get a named value, returns the default if the name doesn't exist
Definition: cryptlib.h:268
virtual void Load(BufferedTransformation &bt)
load key from a BufferedTransformation
Definition: cryptlib.h:1071
virtual unsigned int OptimalNumberOfParallelBlocks() const
return number of blocks that can be processed in parallel, for bit-slicing implementations ...
Definition: cryptlib.h:456
virtual bool NeedsPrespecifiedDataLengths() const
if this function returns true, SpecifyDataLengths() must be called before attempting to input data ...
Definition: cryptlib.h:645
this indicates that a member function was called in the wrong state, for example trying to encrypt a ...
Definition: cryptlib.h:630
interface for public-key signers
Definition: cryptlib.h:1346
virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
throws InvalidMaterial if this object fails Validate() test
Definition: cryptlib.h:1058
interface for public-key encryptors
Definition: cryptlib.h:1223
virtual unsigned int OptimalBlockSize() const
input to Update() should have length a multiple of this for optimal speed
Definition: cryptlib.h:562
CipherDir
used to specify a direction for a cipher to operate in (encrypt or decrypt)
Definition: cryptlib.h:92
void BERDecode(BufferedTransformation &bt)
for backwards compatibility, calls AccessMaterial().Load(bt)
Definition: cryptlib.h:1142
exception thrown by a class when Flush(true) is called but it can't completely flush its buffers ...
Definition: cryptlib.h:172
virtual void Save(BufferedTransformation &bt) const
save key into a BufferedTransformation
Definition: cryptlib.h:1064
exception thrown when trying to retrieve a value using a different type than expected ...
Definition: cryptlib.h:230
CryptoMaterial & AccessMaterial()
returns a reference to the crypto material used by this object
Definition: cryptlib.h:1167
interface for asymmetric algorithms using private keys
Definition: cryptlib.h:1164
void ProcessBlock(byte *inoutBlock) const
encrypt or decrypt one block in place
Definition: cryptlib.h:440
virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
truncated version of VerifyDigest()
Definition: cryptlib.h:592
BufferedTransformation & TheBitBucket()
returns a reference to a BufferedTransformation object that discards all input
virtual bool IsProbabilistic() const =0
requires a random number generator to sign
virtual bool SupportsPrecomputation() const
Definition: cryptlib.h:1075
virtual bool AllowNonrecoverablePart() const =0
whether or not a non-recoverable message part can be signed
virtual bool CanIncorporateEntropy() const
returns true if IncorporateEntropy is implemented
Definition: cryptlib.h:675
std::string GetValueNames() const
get a list of value names that can be retrieved
Definition: cryptlib.h:275
interface for random number generators
Definition: cryptlib.h:668
unsigned int TagSize() const
same as DigestSize()
Definition: cryptlib.h:555
void ProcessString(byte *inoutString, size_t length)
same as ProcessData(inoutString, inoutString, length)
Definition: cryptlib.h:498
virtual void Seek(lword n)
for random access ciphers, seek to an absolute position
Definition: cryptlib.h:510
virtual size_t SignatureLength() const =0
signature length if it only depends on the key, otherwise 0
virtual lword MaxFooterLength() const
the maximum length of AAD that can be input after the encrypted data
Definition: cryptlib.h:642
interface for buffered transformations
Definition: cryptlib.h:770
interface for private keys
Definition: cryptlib.h:1121
interface for cloning objects, this is not implemented by most classes yet
Definition: cryptlib.h:325
virtual unsigned int MinIVLength() const
returns minimal length of IVs accepted by this object
Definition: cryptlib.h:397
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
Definition: cryptlib.h:1168
bool GetThisPointer(T *&p) const
get a pointer to this object, as a pointer to T
Definition: cryptlib.h:254
bool GetIntValue(const char *name, int &value) const
get a named value with type int
Definition: cryptlib.h:281
virtual bool IsValidKeyLength(size_t n) const
returns whether n is a valid key length
Definition: cryptlib.h:362
data integerity check (such as CRC or MAC) failed
Definition: cryptlib.h:121
interface for one direction (encryption or decryption) of a block cipher
Definition: cryptlib.h:603
interface for objects that you can wait for
Definition: cryptlib.h:720
virtual unsigned int GetOptimalBlockSizeUsed() const
returns how much of the current block is used up
Definition: cryptlib.h:482
size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
input multiple bytes that may be modified by callee
Definition: cryptlib.h:803
virtual size_t MaxRecoverableLength() const =0
length of longest message that can be recovered, or 0 if this signature scheme does not support messa...
interface for domains of simple key agreement protocols
Definition: cryptlib.h:1430
virtual unsigned int GetMaxWaitObjectCount() const =0
maximum number of wait objects that this object can return
used to return decoding results
Definition: cryptlib.h:197
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
retrieve previously saved precomputation
Definition: cryptlib.h:1083
Algorithm(bool checkSelfTestStatus=true)
exception thrown when trying to encrypt plaintext of invalid length
Definition: cryptlib.h:1227
bool CanUsePredictableIVs() const
returns whether this object can use random but possibly predictable IVs (in addition to ones returned...
Definition: cryptlib.h:389
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const
decrypt a fixed size ciphertext
Definition: cryptlib.h:1269
received input data that doesn't conform to expected format
Definition: cryptlib.h:123
bool GetValue(const char *name, T &value) const
get a named value, returns true if the name exists
Definition: cryptlib.h:261
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:899
interface for public-key decryptors
Definition: cryptlib.h:1251
virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const &callStack)=0
put wait objects into container
int GetIntValueWithDefault(const char *name, int defaultValue) const
get a named value with type int, with default
Definition: cryptlib.h:285
exception thrown by a class if a non-implemented method is called
Definition: cryptlib.h:165
key too short exception, may be thrown by any function in this class if the private or public key is ...
Definition: cryptlib.h:1295
size_t Put(byte inByte, bool blocking=true)
input a byte for processing
Definition: cryptlib.h:784
virtual unsigned int OptimalBlockSize() const
returns the input block size that is most efficient for this cipher
Definition: cryptlib.h:480
virtual size_t FixedCiphertextLength() const
return fixed ciphertext length, if one exists, otherwise return 0
Definition: cryptlib.h:1211
const std::string DEFAULT_CHANNEL
the default channel for BufferedTransformation, equal to the empty string
virtual void Restart()
discard the current state, and restart with a new message
Definition: cryptlib.h:548
void ProcessBlock(const byte *inBlock, byte *outBlock) const
encrypt or decrypt one block
Definition: cryptlib.h:436
bool IsResynchronizable() const
returns whether this object can be resynchronized (i.e. supports initialization vectors) ...
Definition: cryptlib.h:385
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
Definition: cryptlib.h:1180
interface for encoding and decoding ASN1 objects
Definition: cryptlib.h:1633
StreamTransformation & Ref()
return a reference to this object, useful for passing a temporary object to a function that takes a n...
Definition: cryptlib.h:473
virtual unsigned int MandatoryBlockSize() const
returns block size, if input must be processed in blocks, otherwise 1
Definition: cryptlib.h:476
virtual void Resynchronize(const byte *iv, int ivLength=-1)
resynchronize with an IV. ivLength=-1 means use IVSize()
Definition: cryptlib.h:401
virtual size_t MaxSignatureLength(size_t recoverablePartLength=0) const
maximum signature length produced for a given length of recoverable message part
Definition: cryptlib.h:1307
void ProcessString(byte *outString, const byte *inString, size_t length)
same as ProcessData(outString, inString, length)
Definition: cryptlib.h:501
bool CanUseStructuredIVs() const
returns whether this object can use structured IVs, for example a counter (in addition to ones return...
Definition: cryptlib.h:391
interface for one direction (encryption or decryption) of a stream cipher or cipher mode ...
Definition: cryptlib.h:610
lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
copy copyMax bytes of the buffered output, starting at position (relative to current position)...
Definition: cryptlib.h:910
multiple precision integer and basic arithmetics
Definition: integer.h:26
invalid key exception, may be thrown by any function in this class if the private or public key has a...
Definition: cryptlib.h:1288
keying interface for crypto algorithms that take byte strings as keys
Definition: cryptlib.h:346
virtual std::string AlgorithmName() const
returns name of this algorithm, not universally implemented yet
Definition: cryptlib.h:342
virtual BufferedTransformation * AttachedTransformation()
returns the object immediately attached to this object or NULL for no attachment
Definition: cryptlib.h:1010
HashTransformation & Ref()
return a reference to this object, useful for passing a temporary object to a function that takes a n...
Definition: cryptlib.h:534
virtual void SetAutoSignalPropagation(int propagation)
set propagation of automatically generated and transferred signals
Definition: cryptlib.h:856
interface for asymmetric algorithms using public keys
Definition: cryptlib.h:1151
virtual size_t FixedMaxPlaintextLength() const
return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0 ...
Definition: cryptlib.h:1214
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
Definition: cryptlib.h:1156
virtual unsigned int BlockSize() const
block size of underlying compression function, or 0 if not block based
Definition: cryptlib.h:559
virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0
length of longest message that can be recovered from a signature of given length, or 0 if this signat...
const NameValuePairs & g_nullNameValuePairs
empty set of name-value pairs
unsigned int DigestSize() const
should not be called on PK_MessageAccumulator
Definition: cryptlib.h:1337
interface for public-key signers and verifiers
Definition: cryptlib.h:1284
interface for the data processing part of stream ciphers
Definition: cryptlib.h:469
virtual bool Verify(const byte *digest)
verify that digest is a valid digest for the current message, then reinitialize the object ...
Definition: cryptlib.h:574
RandomNumberGenerator & NullRNG()
returns a reference that can be passed to functions that ask for a RNG but doesn't actually use it ...
virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
truncated version of CalculateDigest()
Definition: cryptlib.h:585
const unsigned long INFINITE_TIME
used to represent infinite time
Definition: cryptlib.h:95
virtual unsigned int MaxIVLength() const
returns maximal length of IVs accepted by this object
Definition: cryptlib.h:399
interface for all crypto algorithms
Definition: cryptlib.h:335
size_t Put(const byte *inString, size_t length, bool blocking=true)
input multiple bytes
Definition: cryptlib.h:787
unsigned int DefaultIVLength() const
returns default length of IVs accepted by this object
Definition: cryptlib.h:395
virtual bool IsPermutation() const
returns true if this is a permutation (i.e. there is an inverse transformation)
Definition: cryptlib.h:450
virtual void BEREncode(BufferedTransformation &bt) const
encode this object into a BufferedTransformation, using BER
Definition: cryptlib.h:1643
interface for accumulating messages to be signed or verified
Definition: cryptlib.h:1333
virtual Clonable * Clone() const
this is not implemented by most classes yet
Definition: cryptlib.h:330
virtual void Detach(BufferedTransformation *newAttachment=0)
delete the current attachment chain and replace it with newAttachment
Definition: cryptlib.h:1015
exception thrown by decryption filters when trying to decrypt an invalid ciphertext ...
Definition: cryptlib.h:158
interface for key agreement algorithms
Definition: cryptlib.h:1176
thrown by objects that have not implemented nonblocking input processing
Definition: cryptlib.h:820
virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
use this if your input is in one piece and you don't want to call Update() and Final() separately ...
Definition: cryptlib.h:568
static void ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
used by derived classes to check for type mismatch
Definition: cryptlib.h:289
CryptoMaterial & AccessMaterial()
returns a reference to the crypto material used by this object
Definition: cryptlib.h:1155
interface for public-key signature verifiers
Definition: cryptlib.h:1387
virtual byte * CreateUpdateSpace(size_t &size)
request space to write input into
Definition: cryptlib.h:540
void Shuffle(IT begin, IT end)
randomly shuffle the specified array, resulting permutation is uniformly distributed ...
Definition: cryptlib.h:697
virtual bool SignatureUpfront() const
if this function returns true, during verification you must input the signature before the message...
Definition: cryptlib.h:1323
interface for hash functions and data processing part of MACs
Definition: cryptlib.h:530
interface for crypto material, such as public and private keys, and crypto parameters ...
Definition: cryptlib.h:1034
virtual byte * CreatePutSpace(size_t &size)
request space which can be written into by the caller, and then used as input to Put() ...
Definition: cryptlib.h:798
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
generate a random key or crypto parameters
Definition: cryptlib.h:1106
void DEREncode(BufferedTransformation &bt) const
for backwards compatibility, calls GetMaterial().Save(bt)
Definition: cryptlib.h:1145
CryptoMaterial & AccessMaterial()
returns a reference to the crypto material used by this object
Definition: cryptlib.h:1179
invalid function argument
Definition: cryptlib.h:117
interface for generatable crypto material, such as private keys and crypto parameters ...
Definition: cryptlib.h:1100
virtual bool RecoverablePartFirst() const =0
whether you must input the recoverable part before the non-recoverable part during signing ...
interface for crypto prameters
Definition: cryptlib.h:1127
BufferedTransformation & Ref()
return a reference to this object, useful for passing a temporary object to a function that takes a n...
Definition: cryptlib.h:779
namespace containing value name definitions
Definition: argnames.h:8
BufferedTransformation received a Flush(true) signal but can't flush buffers.
Definition: cryptlib.h:119
interface for public keys
Definition: cryptlib.h:1115
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:906
interface for the data processing part of block ciphers
Definition: cryptlib.h:428
interface for domains of authenticated key agreement protocols
Definition: cryptlib.h:1468
void TruncatedFinal(byte *digest, size_t digestSize)
should not be called on PK_MessageAccumulator
Definition: cryptlib.h:1340
a method is not implemented
Definition: cryptlib.h:115
byte ProcessByte(byte input)
implemented as {ProcessData(&input, &input, 1); return input;}
Definition: cryptlib.h:504
const std::string AAD_CHANNEL
channel for additional authenticated data, equal to "AAD"
error reading from input device or writing to output device
Definition: cryptlib.h:125
virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
input multiple bytes that may be modified by callee for blocking or non-blocking processing ...
Definition: cryptlib.h:816
virtual void Final(byte *digest)
compute hash for current message, then restart for a new message
Definition: cryptlib.h:544
exception thrown when input data is received that doesn't conform to expected format ...
Definition: cryptlib.h:151
virtual void Precompute(unsigned int n)
do precomputation
Definition: cryptlib.h:1080
virtual unsigned int MinLastBlockSize() const
returns the minimum size of the last block, 0 indicating the last block is not special ...
Definition: cryptlib.h:495
virtual bool Attachable()
returns whether this object allows attachment
Definition: cryptlib.h:1008
virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
use this if your input is in one piece and you don't want to call Update() and Verify() separately ...
Definition: cryptlib.h:578
virtual void IncorporateEntropy(const byte *input, size_t length)
update RNG state with additional unpredictable values
Definition: cryptlib.h:672
interface for retrieving values given their names
Definition: cryptlib.h:224
BER Decode Exception Class, may be thrown during an ASN1 BER decode operation.
Definition: cryptlib.h:1625