📄 cryptlib.h
字号:
// cryptlib.h - written and placed in the public domain by Wei Dai/*! \file This file contains the declarations for the abstract base classes that provide a uniform interface to this library.*//*! \mainpage <a href="http://www.cryptopp.com">Crypto++</a> Reference Manual<dl><dt>Abstract Base Classes<dd> cryptlib.h<dt>Algebraic Structures<dd> Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver, ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP<dt>Block Ciphers (in ECB mode)<dd> 3way.h, blowfish.h, cast.h, des.h, diamond.h, gost.h, idea.h, lubyrack.h, mars.h, mdc.h, rc2.h, rc5.h, rc6.h, rijndael.h, safer.h, serpent.h, shark.h, skipjack.h, square.h, tea.h, twofish.h<dt>Block Cipher Modes<dd> modes.h, cbc.h<dt>Compression<dd> Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor<dt>Secret Sharing and Information Dispersal<dd> SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery<dt>Stream Ciphers<dd> ARC4, PanamaCipher, BlumBlumShub, SEAL, SapphireEncryption, WAKEEncryption<dt>Hash Functions<dd> HAVAL, MD2, MD5, PanamaHash, RIPEMD160, SHA, SHA256, SHA384, SHA512, Tiger<dt>Non-Cryptographic Checksums<dd> CRC32, Adler32<dt>Message Authentication Codes<dd> MD5MAC, XMACC, HMAC, CBC_MAC, DMAC, PanamaMAC<dt>Random Number Generators<dd> NullRNG, LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool<dt>Public Key Cryptography<dd> blumgold.h, dh.h, dh2.h, dsa.h, eccrypto.h, luc.h, mqv.h, nr.h, rsa.h, rabin.h, rw.h, xtrcrypt.h<dt>Input Source Classes<dd> StringSource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource<dt>Output Sink Classes<dd> StringSinkTemplate, ArraySink, FileSink, SocketSink, WindowsPipeSink<dt>Filter Wrappers<dd> StreamCipherFilter, HashFilter, HashVerifier, SignerFilter, VerifierFilter<dt>Binary to Text Encoders and Decoders<dd> HexEncoder, HexDecoder, Base64Encoder, Base64Decoder<dt>Wrappers for OS features<dd> Timer, Socket, WindowsHandle, WindowsReadPipe, WindowsWritePipe</dl><p>This reference manual is very much a work in progress. Many classes are still lacking detailed descriptions.<p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.<p>Thanks to Ryan Phillips for providing the Doxygen configuration fileand getting me started with this manual.*/#ifndef CRYPTOPP_CRYPTLIB_H#define CRYPTOPP_CRYPTLIB_H#include "config.h"#include <limits.h>#include <exception>#include <string>NAMESPACE_BEGIN(CryptoPP)//! base class for all exceptions thrown by Crypto++class Exception : public std::exception{public: explicit Exception(const std::string &s) : m_what(s) {} virtual ~Exception() throw() {} const char *what() const throw() {return (m_what.c_str());} const std::string &GetWhat() const {return m_what;} void SetWhat(const std::string &s) {m_what = s;}private: std::string m_what;};//! used to specify a direction for a cipher to operate in (encrypt or decrypt)enum CipherDir { //! ENCRYPTION, //! DECRYPTION};//! abstract base class for block ciphers/*! All classes derived from BlockTransformation are block ciphers in ECB mode (for example the DESEncryption class), which are stateless. These classes should not be used directly, but only in combination with a mode class (see CipherMode). Note: BlockTransformation objects may assume that pointers to input and output blocks are aligned on 32-bit word boundaries.*/class BlockTransformation{public: //! virtual ~BlockTransformation() {} //! encrypt or decrypt one block in place /*! \pre size of inoutBlock == BlockSize() */ virtual void ProcessBlock(byte *inoutBlock) const =0; //! encrypt or decrypt one block, may assume inBlock != outBlock /*! \pre size of inBlock and outBlock == BlockSize() */ virtual void ProcessBlock(const byte *inBlock, byte *outBlock) const =0; //! block size of the cipher in bytes virtual unsigned int BlockSize() const =0;};//! provides an implementation of BlockSize()template <unsigned int N>class FixedBlockSize : public BlockTransformation{public: enum {BLOCKSIZE = N}; virtual unsigned int BlockSize() const {return BLOCKSIZE;}};//! abstract base class for stream ciphersclass StreamCipher{public: //! virtual ~StreamCipher() {} //! encrypt or decrypt one byte virtual byte ProcessByte(byte input) =0; //! encrypt or decrypt an array of bytes of specified length in place virtual void ProcessString(byte *inoutString, unsigned int length); //! encrypt or decrypt an array of bytes of specified length, may assume inString != outString virtual void ProcessString(byte *outString, const byte *inString, unsigned int length);};//! abstract base class for random access stream ciphersclass RandomAccessStreamCipher : public virtual StreamCipher{public: //! virtual ~RandomAccessStreamCipher() {} /*/ specify that the next byte to be processed is at absolute position n in the plaintext/ciphertext stream */ virtual void Seek(unsigned long n) =0;};//! abstract base class for random number generators/*! All return values are uniformly distributed over the range specified.*/class RandomNumberGenerator{public: //! virtual ~RandomNumberGenerator() {} //! generate new random byte and return it virtual byte GenerateByte() =0; //! generate new random bit and return it /*! Default implementation is to call GenerateByte() and return its parity. */ virtual unsigned int GenerateBit(); //! generate a random 32 bit word in the range min to max, inclusive virtual word32 GenerateWord32(word32 a=0, word32 b=0xffffffffL); //! generate random array of bytes //* Default implementation is to call GenerateByte() size times. virtual void GenerateBlock(byte *output, unsigned int size); //! randomly shuffle the specified array, resulting permutation is uniformly distributed template <class IT> void Shuffle(IT begin, IT end) { for (; begin != end; ++begin) std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1)); } // for backwards compatibility, maybe be remove later byte GetByte() {return GenerateByte();} unsigned int GetBit() {return GenerateBit();} word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);} word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);} void GetBlock(byte *output, unsigned int size) {GenerateBlock(output, size);}};//! abstract base class for hash functions/*! HashModule objects are stateful. They are created in an initial state, change state as Update() is called, and return to the initial state when Final() is called. This interface allows a large message to be hashed in pieces by calling Update() on each piece followed by calling Final().*/class HashModule{public: //! virtual ~HashModule() {} //! process more input virtual void Update(const byte *input, unsigned int length) =0; /*/ calculate hash for the current message (the concatenation of all inputs passed in via Update()), then reinitialize the object */ //* Precondition: size of digest == DigestSize(). virtual void Final(byte *digest) =0; //! size of the hash returned by Final() virtual unsigned int DigestSize() const =0; //! use this if your input is short and you don't want to call Update() and Final() seperately virtual void CalculateDigest(byte *digest, const byte *input, int length) {Update(input, length); Final(digest);} //! verify that digest is a valid digest for the current message, then reinitialize the object /*! Default implementation is to call Final() and do a bitwise comparison between its output and digest. */ virtual bool Verify(const byte *digest); //! use this if your input is short and you don't want to call Update() and Verify() seperately virtual bool VerifyDigest(const byte *digest, const byte *input, int length) {Update(input, length); return Verify(digest);}};//! abstract base class for message authentication codes/*! The main differences between a MAC and an hash function (in terms of programmatic interface) is that a MAC is keyed, and that calculating a MAC for the same message twice may produce two different results so verifying a MAC may not be simply recalculating it and doing a bitwise comparison.*/class MessageAuthenticationCode : public virtual HashModule{public: //! virtual ~MessageAuthenticationCode() {}};//! abstract base class for buffered transformations/*! BufferedTransformation is a generalization of BlockTransformation, StreamCipher, and HashModule. A buffered transformation is an object that takes a stream of bytes as input (this may be done in stages), does some computation on them, and then places the result into an internal buffer for later retrieval. Any partial result already in the output buffer is not modified by further input. Computation is generally done as soon as possible, but some buffering on the input may be done for performance reasons. \nosubgrouping*/class BufferedTransformation{public: //! virtual ~BufferedTransformation() {} //! \name INPUT //@{ //! input a byte for processing virtual void Put(byte inByte) =0; //! input multiple bytes virtual void Put(const byte *inString, unsigned int length) =0; //! input a 16-bit word, big-endian or little-endian depending on highFirst void PutWord16(word16 value, bool highFirst=true); //! input a 32-bit word void PutWord32(word32 value, bool highFirst=true); //@} //! \name SIGNALS //@{ //! process everything in internal buffers and output them /*! throws exception if completeFlush == true and it's not possible to flush everything */ virtual void Flush(bool completeFlush, int propagation=-1); //! mark end of an input segment, message, or packet /*! propagation != 0 means pass on the signal to attached BufferedTransformation objects, with propagation decremented at each step until it reaches 0. -1 means unlimited propagation. */ virtual void MessageEnd(int propagation=-1); //! same as Put() followed by MessageEnd() but may be more efficient virtual void PutMessageEnd(const byte *inString, unsigned int length, int propagation=-1); //! mark end of a series of messages /*! There should be a MessageEnd immediately before MessageSeriesEnd. */ virtual void MessageSeriesEnd(int propagation=-1); //! set propagation of automatically generated and transfered signals /*! propagation == 0 means do not automaticly generate signals */ virtual void SetAutoSignalPropagation(int propagation) {} //! virtual int GetAutoSignalPropagation() const {return 0;} // for backwards compatibility void Close() {MessageEnd();} //@} //! \name ERRORS //@{ //! error types enum ErrorType { //! received a Flush(true) signal but can't flush buffers CANNOT_FLUSH, //! data integerity check (such as CRC or MAC) failed DATA_INTEGRITY_CHECK_FAILED, //! received input data that doesn't conform to expected format INVALID_DATA_FORMAT, //! error reading from input device INPUT_ERROR, //! error writing to output device OUTPUT_ERROR, //! some error not belong to any of the above categories OTHER_ERROR }; //! exception thrown by BufferedTransformation class Err : public Exception { public: Err(ErrorType errorType, const std::string &s=""); ErrorType GetErrorType() const {return m_errorType;} void SetErrorType(ErrorType errorType) {m_errorType = errorType;} private: ErrorType m_errorType; }; //@} //! \name RETRIEVAL OF ONE MESSAGE //@{ //! returns number of bytes that is currently ready for retrieval /*! All retrieval functions return the actual number of bytes retrieved, which is the lesser of the request number and MaxRetrievable(). */ virtual unsigned long MaxRetrievable() const; // old mispelled name unsigned long MaxRetrieveable() const {return MaxRetrievable();} //! returns whether any bytes are currently ready for retrieval virtual bool AnyRetrievable() const; //! try to retrieve a single byte virtual unsigned int Get(byte &outByte); //! try to retrieve multiple bytes virtual unsigned int Get(byte *outString, unsigned int getMax); //! peek at the next byte without removing it from the output buffer virtual unsigned int Peek(byte &outByte) const; //! peek at multiple bytes without removing them from the output buffer virtual unsigned int Peek(byte *outString, unsigned int peekMax) const; //! try to retrieve a 16-bit word, big-endian or little-endian depending on highFirst unsigned int GetWord16(word16 &value, bool highFirst=true); //! try to retrieve a 32-bit word unsigned int GetWord32(word32 &value, bool highFirst=true); //! try to peek at a 16-bit word, big-endian or little-endian depending on highFirst unsigned int PeekWord16(word16 &value, bool highFirst=true); //! try to peek at a 32-bit word unsigned int PeekWord32(word32 &value, bool highFirst=true); //! move transferMax bytes of the buffered output to target as input virtual unsigned long TransferTo(BufferedTransformation &target, unsigned long transferMax=ULONG_MAX); //! discard skipMax bytes from the output buffer virtual unsigned long Skip(unsigned long skipMax=ULONG_MAX); //! copy copyMax bytes of the buffered output to target as input virtual unsigned long CopyTo(BufferedTransformation &target, unsigned long copyMax=ULONG_MAX) const; //@} //! \name RETRIEVAL OF MULTIPLE MESSAGES //@{ //! virtual unsigned long TotalBytesRetrievable() const; //! number of times MessageEnd() has been received minus messages retrieved or skipped virtual unsigned int NumberOfMessages() const; //! returns true if NumberOfMessages() > 0 virtual bool AnyMessages() const; //! start retrieving the next message /*! Returns false if no more messages exist or this message is not completely retrieved. */ virtual bool GetNextMessage(); //! skip count number of messages virtual unsigned int SkipMessages(unsigned int count=UINT_MAX); //! virtual unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX); //! virtual unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX) const; //! virtual void SkipAll(); //! virtual void TransferAllTo(BufferedTransformation &target);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -