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

📄 cryptlib.h

📁 hashish-1.1b加密算法库c++
💻 H
📖 第 1 页 / 共 5 页
字号:
// ********************************************************//! interface for cloning objects, this is not implemented by most classes yetclass Clonable{public:	virtual ~Clonable() {}	//! this is not implemented by most classes yet	virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");}	// TODO: make this =0};//! interface for all crypto algorithmsclass Algorithm : public Clonable{public:	/*! When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,		this constructor throws SelfTestFailure if the self test hasn't been run or fails. */	Algorithm(bool checkSelfTestStatus = true);	//! returns name of this algorithm, not universally implemented yet	virtual std::string AlgorithmName() const {return "unknown";}};//! keying interface for crypto algorithms that take byte strings as keysclass SimpleKeyingInterface{public:	//! returns smallest valid key length in bytes */	virtual unsigned int MinKeyLength() const =0;	//! returns largest valid key length in bytes */	virtual unsigned int MaxKeyLength() const =0;	//! returns default (recommended) key length in bytes */	virtual unsigned int DefaultKeyLength() const =0;	//! returns the smallest valid key length in bytes that is >= min(n, GetMaxKeyLength())	virtual unsigned int GetValidKeyLength(unsigned int n) const =0;	//! returns whether n is a valid key length	virtual bool IsValidKeyLength(unsigned int n) const		{return n == GetValidKeyLength(n);}	//! set or reset the key of this object	/*! \param params is used to specify Rounds, BlockSize, etc */	virtual void SetKey(const byte *key, unsigned int length, const NameValuePairs &params = g_nullNameValuePairs) =0;	//! calls SetKey() with an NameValuePairs object that just specifies "Rounds"	void SetKeyWithRounds(const byte *key, unsigned int length, int rounds);	//! calls SetKey() with an NameValuePairs object that just specifies "IV"	void SetKeyWithIV(const byte *key, unsigned int length, const byte *iv);	enum IV_Requirement {STRUCTURED_IV = 0, RANDOM_IV, UNPREDICTABLE_RANDOM_IV, INTERNALLY_GENERATED_IV, NOT_RESYNCHRONIZABLE};	//! returns the minimal requirement for secure IVs	virtual IV_Requirement IVRequirement() const =0;	//! returns whether this object can be resynchronized (i.e. supports initialization vectors)	/*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */	bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}	//! returns whether this object can use random IVs (in addition to ones returned by GetNextIV)	bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}	//! returns whether this object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV)	bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}	//! returns whether this object can use structured IVs, for example a counter (in addition to ones returned by GetNextIV)	bool CanUseStructuredIVs() const {return IVRequirement() <= STRUCTURED_IV;}	//! returns size of IVs used by this object	virtual unsigned int IVSize() const {throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");}	//! resynchronize with an IV	virtual void Resynchronize(const byte *IV) {throw NotImplemented("SimpleKeyingInterface: this object doesn't support resynchronization");}	//! get a secure IV for the next message	/*! This method should be called after you finish encrypting one message and are ready to start the next one.		After calling it, you must call SetKey() or Resynchronize() before using this object again. 		This method is not implemented on decryption objects. */	virtual void GetNextIV(byte *IV) {throw NotImplemented("SimpleKeyingInterface: this object doesn't support GetNextIV()");}protected:	void ThrowIfInvalidKeyLength(const Algorithm &algorithm, unsigned int length);	inline void AssertValidKeyLength(unsigned int length) const	{		assert(IsValidKeyLength(length));	}};//! interface for the data processing part of block ciphers/*! Classes derived from BlockTransformation are block ciphers	in ECB mode (for example the DES::Encryption class), which are stateless,	and they can make assumptions about the memory alignment of their inputs and outputs.	These classes should not be used directly, but only in combination with	a mode class (see CipherModeDocumentation in modes.h).*/class BlockTransformation : public Algorithm{public:	//! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock	virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;	//! encrypt or decrypt one block	/*! \pre size of inBlock and outBlock == BlockSize() */	void ProcessBlock(const byte *inBlock, byte *outBlock) const		{ProcessAndXorBlock(inBlock, NULL, outBlock);}	//! encrypt or decrypt one block in place	void ProcessBlock(byte *inoutBlock) const		{ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);}	//! block size of the cipher in bytes	virtual unsigned int BlockSize() const =0;	//! block pointers must be divisible by this	virtual unsigned int BlockAlignment() const {return 4;}	//! returns true if this is a permutation (i.e. there is an inverse transformation)	virtual bool IsPermutation() const {return true;}	//! returns true if this is an encryption object	virtual bool IsForwardTransformation() const =0;	//! return number of blocks that can be processed in parallel, for bit-slicing implementations	virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}	//! encrypt or decrypt multiple blocks, for bit-slicing implementations	virtual void ProcessAndXorMultipleBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, unsigned int numberOfBlocks) const;};//! interface for the data processing part of stream ciphersclass StreamTransformation : public Algorithm{public:	//! return a reference to this object, 	/*! This function is useful for passing a temporary StreamTransformation object to a 		function that takes a non-const reference. */	StreamTransformation& Ref() {return *this;}	//! returns block size, if input must be processed in blocks, otherwise 1	virtual unsigned int MandatoryBlockSize() const {return 1;}	//! returns the input block size that is most efficient for this cipher	/*! \note optimal input length is n * OptimalBlockSize() - GetOptimalBlockSizeUsed() for any n > 0 */	virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}	//! returns how much of the current block is used up	virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}	//! returns how input should be aligned for optimal performance	virtual unsigned int OptimalDataAlignment() const {return 1;}	//! encrypt or decrypt an array of bytes of specified length	/*! \note either inString == outString, or they don't overlap */	virtual void ProcessData(byte *outString, const byte *inString, unsigned int length) =0;	//! for ciphers where the last block of data is special, encrypt or decrypt the last block of data	/*! For now the only use of this function is for CBC-CTS mode. */	virtual void ProcessLastBlock(byte *outString, const byte *inString, unsigned int length);	//! returns the minimum size of the last block, 0 indicating the last block is not special	virtual unsigned int MinLastBlockSize() const {return 0;}	//! same as ProcessData(inoutString, inoutString, length)	inline void ProcessString(byte *inoutString, unsigned int length)		{ProcessData(inoutString, inoutString, length);}	//! same as ProcessData(outString, inString, length)	inline void ProcessString(byte *outString, const byte *inString, unsigned int length)		{ProcessData(outString, inString, length);}	//! implemented as {ProcessData(&input, &input, 1); return input;}	inline byte ProcessByte(byte input)		{ProcessData(&input, &input, 1); return input;}	//! returns whether this cipher supports random access	virtual bool IsRandomAccess() const =0;	//! for random access ciphers, seek to an absolute position	virtual void Seek(dword n)	{		assert(!IsRandomAccess());		throw NotImplemented("StreamTransformation: this object doesn't support random access");	}	//! returns whether this transformation is self-inverting (e.g. xor with a keystream)	virtual bool IsSelfInverting() const =0;	//! returns whether this is an encryption object	virtual bool IsForwardTransformation() const =0;};//! interface for hash functions and data processing part of MACs/*! HashTransformation 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 HashTransformation : public Algorithm{public:	//! process more input	virtual void Update(const byte *input, unsigned int length) =0;	//! request space to write input into	virtual byte * CreateUpdateSpace(unsigned int &size) {size=0; return NULL;}	//! compute hash for current message, then restart for a new message	/*!	\pre size of digest == DigestSize(). */	virtual void Final(byte *digest)		{TruncatedFinal(digest, DigestSize());}	//! discard the current state, and restart with a new message	virtual void Restart()		{TruncatedFinal(NULL, 0);}	//! size of the hash returned by Final()	virtual unsigned int DigestSize() const =0;	//! input to Update() should have length a multiple of this for optimal speed	virtual unsigned int OptimalBlockSize() const {return 1;}	//! returns how input should be aligned for optimal performance	virtual unsigned int OptimalDataAlignment() const {return 1;}	//! use this if your input is in one piece and you don't want to call Update() and Final() separately	virtual void CalculateDigest(byte *digest, const byte *input, unsigned 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)		{return TruncatedVerify(digest, DigestSize());}	//! use this if your input is in one piece and you don't want to call Update() and Verify() separately	virtual bool VerifyDigest(const byte *digest, const byte *input, unsigned int length)		{Update(input, length); return Verify(digest);}	//! truncated version of Final()	virtual void TruncatedFinal(byte *digest, unsigned int digestSize) =0;	//! truncated version of CalculateDigest()	virtual void CalculateTruncatedDigest(byte *digest, unsigned int digestSize, const byte *input, unsigned int length)		{Update(input, length); TruncatedFinal(digest, digestSize);}	//! truncated version of Verify()	virtual bool TruncatedVerify(const byte *digest, unsigned int digestLength);	//! truncated version of VerifyDigest()	virtual bool VerifyTruncatedDigest(const byte *digest, unsigned int digestLength, const byte *input, unsigned int length)		{Update(input, length); return TruncatedVerify(digest, digestLength);}protected:	void ThrowIfInvalidTruncatedSize(unsigned int size) const;};//! .template <class T>class SimpleKeyedTransformation : public T, public SimpleKeyingInterface{public:	void ThrowIfInvalidKeyLength(unsigned int length)		{SimpleKeyingInterface::ThrowIfInvalidKeyLength(*this, length);}};//! .typedef HashTransformation HashFunction;#ifdef CRYPTOPP_DOXYGEN_PROCESSING//! These objects usually should not be used directly. See BlockTransformation for more details.class BlockCipher : public BlockTransformation, public SimpleKeyingInterface {};//! interface for stream ciphersclass SymmetricCipher : public StreamTransformation, public SimpleKeyingInterface {};//! interface for message authentication codesclass MessageAuthenticationCode : public HashTransformation, public SimpleKeyingInterface {};#elsetypedef SimpleKeyedTransformation<BlockTransformation> BlockCipher;typedef SimpleKeyedTransformation<StreamTransformation> SymmetricCipher;typedef SimpleKeyedTransformation<HashTransformation> MessageAuthenticationCode;#endif#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITYtypedef SymmetricCipher StreamCipher;#endif//! interface for random number generators/*! All return values are uniformly distributed over the range specified.*/class RandomNumberGenerator : public Algorithm{public:	//! 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);	//! generate and discard n bytes	/*! Default implementation is to call GenerateByte() n times. */	virtual void DiscardBytes(unsigned int n);	//! randomly shuffle the specified array, resulting permutation is uniformly distributed	template <class IT> void Shuffle(IT begin, IT end)

⌨️ 快捷键说明

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