Coverage Report

Created: 2024-11-21 07:03

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