monotone

monotone Mtn Source Tree

Root/cryptopp/cryptlib.h

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

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status