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