⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cryptlib.h

📁 伯克利做的SFTP安全文件传输协议
💻 H
📖 第 1 页 / 共 2 页
字号:
// cryptlib.h - written and placed in the public domain by Wei Dai// This file contains the declarations for the abstract base// classes that provide a uniform interface to this library.#ifndef CRYPTLIB_H#define CRYPTLIB_H#ifdef SAFETP#  include "crconfig.h"     // so we can define our own config.h if necessary#else#  include "config.h"#endif#ifdef SAFETP   // SM: my modifications do two things:   //   1. Derive CryptlibException from xBase instead of std::exception.   //      This avoids having to catch both std::exception and xBase for   //      catch-all situations.  Deriving xBase from std::exception is also   //      a possibility, but we decided not to do it.  (Won't fill up this   //      file (any more than I already have) with rationale.)   //   2. Eliminate crypto++'s use of std::string, since it conflicts with   //      'string' defined in str.h (actually 'mystring', but it still   //      conflicts, it turns out).#  include "exc.h"       // xBase#else#  include <exception>#  include <string>#endif/// base class for all exceptions thrown by Crypto++#ifdef SAFETPclass CryptlibException : public xBase{public:	explicit CryptlibException(const string& s) : xBase(s) {}	virtual ~CryptlibException() {}	char const *what() const { return why(); }     // :)};#elseclass CryptlibException : public std::exception{public:	explicit CryptlibException(const std::string& s) : m_what(s) {}	virtual ~CryptlibException() {}	const char *what() const {return (m_what.c_str());}private:	std::string m_what;};#endif // !SAFETP/// used to specify a direction for a cipher to operate in (encrypt or decrypt)enum CipherDir {	///	ENCRYPTION, 	///	DECRYPTION};/// abstract base class for block ciphers/** A particular derived class may change state as blocks are processed,	so the ProcessBlock() functions are not specified to be const.	However, most 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 \Ref{Mode}).  However, if you know what you are doing, and	need to call ProcessBlock() on a const ECB cipher object, you can safely	cast away its constness.	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	// * Precondition: size of inoutBlock == BlockSize().	virtual void ProcessBlock(byte *inoutBlock) =0;	/// encrypt or decrypt one block, may assume inBlock != outBlock	// * Precondition: size of inBlock and outBlock == BlockSize().	virtual void ProcessBlock(const byte *inBlock, byte *outBlock) =0;           	/// block size of the cipher in bytes	virtual unsigned int BlockSize() const =0;};/// 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 GetByte() =0;	/// generate new random bit and return it	/** Default implementation is to call GetByte() and return its parity. */	virtual unsigned int GetBit();	/// generate a random 32 bit word in the range min to max, inclusive	virtual word32 GetLong(word32 a=0, word32 b=0xffffffffL);	/// generate a random 16 bit word in the range min to max, inclusive	virtual word16 GetShort(word16 a=0, word16 b=0xffff)		{return (word16)GetLong(a, b);}	/// generate random array of bytes	// * Default implementation is to call GetByte size times.	virtual void GetBlock(byte *output, unsigned int size);};/// randomly shuffle the specified array, resulting permutation is uniformly distributedtemplate <class T> void Shuffle(RandomNumberGenerator &rng, T *array, unsigned int size){	while (--size)		swap(array[size], array[(unsigned int)rng.GetLong(0, 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;#ifdef SAFETP        // this was (rather clumsily) previously expected to be a symbolic        // constant called DATASIZE, and may be why Wei used templates        // in places and ways he shouldn't have (IMO); it is the size of        // the chunks into which the hash function divides up its input        virtual unsigned int DataSize() const =0;#endif	/// 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);}};/// 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.*/#ifdef SAFETP// SM: for our purposes, we don't need the virtual base class (because// I recoded hmac.h), and I'm suspicious of what g++ will do with itclass MessageAuthenticationCode : public /*virtual*/ HashModule#elseclass MessageAuthenticationCode : public virtual HashModule#endif{public:	///	virtual ~MessageAuthenticationCode() {}	/// verify that mac is a valid MAC for the current message, then reinitialize the object	/** Default implementation is to call Final() and do a bitwise comparison		between its output and mac. */	virtual bool Verify(const byte *mac);	/// use this if your input is short and you don't want to call Update() and Verify() seperately	virtual bool VerifyMAC(const byte *mac, const byte *input, int length)		{Update(input, length); return Verify(mac);}};/// abstract base class for buffered transformations/** BufferedTransformation is a generalization of \Ref{BlockTransformation},	\Ref{StreamCipher}, and \Ref{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.*/class BufferedTransformation{public:	///	virtual ~BufferedTransformation() {}	//@Man: 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;		/// signal that no more input is available		virtual void InputFinished() {}		/// input a 16-bit word, big-endian or little-endian depending on highFirst		void PutShort(word16 value, bool highFirst=true);		/// input a 32-bit word		void PutLong(word32 value, bool highFirst=true);	//@}	//@Man: RETRIEVAL	//@{		/// 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			MaxRetrieveable(). */		virtual unsigned long MaxRetrieveable() =0;		/// try to retrieve a single byte		virtual unsigned int Get(byte &outByte) =0;		/// try to retrieve multiple bytes		virtual unsigned int Get(byte *outString, unsigned int getMax) =0;		/// try to retrieve a 16-bit word, big-endian or little-endian depending on highFirst		int GetShort(word16 &value, bool highFirst=true);		/// try to retrieve a 32-bit word		int GetLong(word32 &value, bool highFirst=true);		/// move all of the buffered output to target as input

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -