Crypto++ 8.1 Free C++ class library of cryptographic schemes

iterhash.h
1 // iterhash.h - originally written and placed in the public domain by Wei Dai
2
3 #ifndef CRYPTOPP_ITERHASH_H
4 #define CRYPTOPP_ITERHASH_H
5
6 #include "cryptlib.h"
7 #include "secblock.h"
8 #include "misc.h"
9 #include "simple.h"
10
11 #if CRYPTOPP_MSC_VERSION
12 # pragma warning(push)
13 # pragma warning(disable: 4231 4275)
14 # if (CRYPTOPP_MSC_VERSION >= 1400)
15 # pragma warning(disable: 6011 6386 28193)
16 # endif
17 #endif
18
19 NAMESPACE_BEGIN(CryptoPP)
20
21 /// \brief Exception thrown when trying to hash more data than is allowed by a hash function
22 class CRYPTOPP_DLL HashInputTooLong : public InvalidDataFormat
23 {
24 public:
25 explicit HashInputTooLong(const std::string &alg)
26 : InvalidDataFormat("IteratedHashBase: input data exceeds maximum allowed by hash function " + alg) {}
27 };
28
29 /// \brief Iterated hash base class
30 /// \tparam T Hash word type
31 /// \tparam BASE HashTransformation derived class
32 /// \details IteratedHashBase provides an interface for block-based iterated hashes
33 /// \sa HashTransformation, MessageAuthenticationCode
34 template <class T, class BASE>
35 class CRYPTOPP_NO_VTABLE IteratedHashBase : public BASE
36 {
37 public:
38 typedef T HashWordType;
39
40 virtual ~IteratedHashBase() {}
41
42 /// \brief Construct an IteratedHashBase
43 IteratedHashBase() : m_countLo(0), m_countHi(0) {}
44
45 /// \brief Provides the input block size most efficient for this cipher.
46 /// \return The input block size that is most efficient for the cipher
47 /// \details The base class implementation returns MandatoryBlockSize().
48 /// \note Optimal input length is
49 /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n > 0</tt>.
50 unsigned int OptimalBlockSize() const {return this->BlockSize();}
51
52 /// \brief Provides input and output data alignment for optimal performance.
53 /// \return the input data alignment that provides optimal performance
54 /// \details OptimalDataAlignment returns the natural alignment of the hash word.
55 unsigned int OptimalDataAlignment() const {return GetAlignmentOf<T>();}
56
57 /// \brief Updates a hash with additional input
58 /// \param input the additional input as a buffer
59 /// \param length the size of the buffer, in bytes
60 void Update(const byte *input, size_t length);
61
62 /// \brief Requests space which can be written into by the caller
63 /// \param size the requested size of the buffer
64 /// \details The purpose of this method is to help avoid extra memory allocations.
65 /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
66 /// size is the requested size of the buffer. When the call returns, size is the size of
67 /// the array returned to the caller.
68 /// \details The base class implementation sets size to 0 and returns NULL.
69 /// \note Some objects, like ArraySink, cannot create a space because its fixed.
70 byte * CreateUpdateSpace(size_t &size);
71
72 /// \brief Restart the hash
73 /// \details Discards the current state, and restart for a new message
74 void Restart();
75
76 /// \brief Computes the hash of the current message
77 /// \param digest a pointer to the buffer to receive the hash
78 /// \param digestSize the size of the truncated digest, in bytes
79 /// \details TruncatedFinal() call Final() and then copies digestSize bytes to digest.
80 /// The hash is restarted the hash for the next message.
81 void TruncatedFinal(byte *digest, size_t digestSize);
82
83 /// \brief Retrieve the provider of this algorithm
84 /// \return the algorithm provider
85 /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
86 /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
87 /// usually indicate a specialized implementation using instructions from a higher
88 /// instruction set architecture (ISA). Future labels may include external hardware
89 /// like a hardware security module (HSM).
90 /// \note Provider is not universally implemented yet.
91 virtual std::string AlgorithmProvider() const { return "C++"; }
92
93 protected:
94 inline T GetBitCountHi() const
95 {return (m_countLo >> (8*sizeof(T)-3)) + (m_countHi << 3);}
96 inline T GetBitCountLo() const
97 {return m_countLo << 3;}
98
99 void PadLastBlock(unsigned int lastBlockSize, byte padFirst=0x80);
100 virtual void Init() =0;
101
102 virtual ByteOrder GetByteOrder() const =0;
103 virtual void HashEndianCorrectedBlock(const HashWordType *data) =0;
104 virtual size_t HashMultipleBlocks(const T *input, size_t length);
105 void HashBlock(const HashWordType *input)
106 {HashMultipleBlocks(input, this->BlockSize());}
107
108 virtual T* DataBuf() =0;
109 virtual T* StateBuf() =0;
110
111 private:
112 T m_countLo, m_countHi;
113 };
114
115 /// \brief Iterated hash base class
116 /// \tparam T_HashWordType Hash word type
117 /// \tparam T_Endianness Endianness type of hash
118 /// \tparam T_BlockSize Block size of the hash
119 /// \tparam T_Base HashTransformation derived class
120 /// \details IteratedHash provides a default implementation for block-based iterated hashes
121 /// \sa HashTransformation, MessageAuthenticationCode
122 template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, class T_Base = HashTransformation>
123 class CRYPTOPP_NO_VTABLE IteratedHash : public IteratedHashBase<T_HashWordType, T_Base>
124 {
125 public:
126 typedef T_Endianness ByteOrderClass;
127 typedef T_HashWordType HashWordType;
128
129 CRYPTOPP_CONSTANT(BLOCKSIZE = T_BlockSize)
130 // BCB2006 workaround: can't use BLOCKSIZE here
131 CRYPTOPP_COMPILE_ASSERT((T_BlockSize & (T_BlockSize - 1)) == 0); // blockSize is a power of 2
132
133 virtual ~IteratedHash() {}
134
135 /// \brief Provides the block size of the hash
136 /// \return the block size of the hash, in bytes
137 /// \details BlockSize() returns <tt>T_BlockSize</tt>.
138 unsigned int BlockSize() const {return T_BlockSize;}
139
140 /// \brief Provides the byte order of the hash
141 /// \returns the byte order of the hash as an enumeration
142 /// \details GetByteOrder() returns <tt>T_Endianness::ToEnum()</tt>.
143 /// \sa ByteOrder()
144 ByteOrder GetByteOrder() const {return T_Endianness::ToEnum();}
145
146 /// \brief Adjusts the byte ordering of the hash
147 /// \param out the output buffer
148 /// \param in the input buffer
149 /// \param byteCount the size of the buffers, in bytes
150 /// \details CorrectEndianess() calls ConditionalByteReverse() using <tt>T_Endianness</tt>.
151 inline void CorrectEndianess(HashWordType *out, const HashWordType *in, size_t byteCount)
152 {
153 CRYPTOPP_ASSERT(in != NULLPTR);
154 CRYPTOPP_ASSERT(out != NULLPTR);
155 CRYPTOPP_ASSERT(IsAligned<T_HashWordType>(in));
156 CRYPTOPP_ASSERT(IsAligned<T_HashWordType>(out));
157
158 ConditionalByteReverse(T_Endianness::ToEnum(), out, in, byteCount);
159 }
160
161 protected:
162 T_HashWordType* DataBuf() {return this->m_data;}
163 FixedSizeSecBlock<T_HashWordType, T_BlockSize/sizeof(T_HashWordType)> m_data;
164 };
165
166 /// \brief Iterated hash with a static transformation function
167 /// \tparam T_HashWordType Hash word type
168 /// \tparam T_Endianness Endianness type of hash
169 /// \tparam T_BlockSize Block size of the hash
170 /// \tparam T_StateSize Internal state size of the hash
171 /// \tparam T_Transform HashTransformation derived class
172 /// \tparam T_DigestSize Digest size of the hash
173 /// \tparam T_StateAligned Flag indicating if state is 16-byte aligned
174 /// \sa HashTransformation, MessageAuthenticationCode
175 template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, unsigned int T_StateSize, class T_Transform, unsigned int T_DigestSize = 0, bool T_StateAligned = false>
176 class CRYPTOPP_NO_VTABLE IteratedHashWithStaticTransform
177 : public ClonableImpl<T_Transform, AlgorithmImpl<IteratedHash<T_HashWordType, T_Endianness, T_BlockSize>, T_Transform> >
178 {
179 public:
180 CRYPTOPP_CONSTANT(DIGESTSIZE = T_DigestSize ? T_DigestSize : T_StateSize)
181
182 virtual ~IteratedHashWithStaticTransform() {}
183
184 /// \brief Provides the digest size of the hash
185 /// \return the digest size of the hash, in bytes
186 /// \details DigestSize() returns <tt>DIGESTSIZE</tt>.
187 unsigned int DigestSize() const {return DIGESTSIZE;}
188
189 protected:
190 IteratedHashWithStaticTransform() {this->Init();}
191 void HashEndianCorrectedBlock(const T_HashWordType *data) {T_Transform::Transform(this->m_state, data);}
192 void Init() {T_Transform::InitState(this->m_state);}
193
194 T_HashWordType* StateBuf() {return this->m_state;}
195 FixedSizeAlignedSecBlock<T_HashWordType, T_BlockSize/sizeof(T_HashWordType), T_StateAligned> m_state;
196 };
197
198 #if !defined(__GNUC__) && !defined(__clang__)
199 CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase<word64, HashTransformation>;
200 CRYPTOPP_STATIC_TEMPLATE_CLASS IteratedHashBase<word64, MessageAuthenticationCode>;
201
202 CRYPTOPP_DLL_TEMPLATE_CLASS IteratedHashBase<word32, HashTransformation>;
203 CRYPTOPP_STATIC_TEMPLATE_CLASS IteratedHashBase<word32, MessageAuthenticationCode>;
204 #endif
205
206 NAMESPACE_END
207
208 #if CRYPTOPP_MSC_VERSION
209 # pragma warning(pop)
210 #endif
211
212 #endif
IteratedHashBase::IteratedHashBase
IteratedHashBase()
Construct an IteratedHashBase.
Definition: iterhash.h:43
simple.h
Classes providing basic library services.
misc.h
Utility functions for the Crypto++ library.
ByteOrder
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:143
ClonableImpl
Base class for identifying alogorithm.
Definition: simple.h:25
IteratedHashWithStaticTransform
Iterated hash with a static transformation function.
Definition: iterhash.h:176
cryptlib.h
Abstract base classes that provide a uniform interface to this library.
IteratedHash::BlockSize
unsigned int BlockSize() const
Provides the block size of the hash.
Definition: iterhash.h:138
HashInputTooLong
Exception thrown when trying to hash more data than is allowed by a hash function.
Definition: iterhash.h:22
secblock.h
Classes and functions for secure memory allocations.
IteratedHash::GetByteOrder
ByteOrder GetByteOrder() const
Provides the byte order of the hash.
Definition: iterhash.h:144
CRYPTOPP_COMPILE_ASSERT
#define CRYPTOPP_COMPILE_ASSERT(expr)
Compile time assertion.
Definition: misc.h:116
ConditionalByteReverse
T ConditionalByteReverse(ByteOrder order, T value)
Reverses bytes in a value depending upon endianness.
Definition: misc.h:2081
FixedSizeAlignedSecBlock
Fixed size stack-based SecBlock with 16-byte alignment.
Definition: secblock.h:1089
IteratedHash::CorrectEndianess
void CorrectEndianess(HashWordType *out, const HashWordType *in, size_t byteCount)
Adjusts the byte ordering of the hash.
Definition: iterhash.h:151
IteratedHashWithStaticTransform::DigestSize
unsigned int DigestSize() const
Provides the digest size of the hash.
Definition: iterhash.h:187
FixedSizeSecBlock
Fixed size stack-based SecBlock.
Definition: secblock.h:1077
CRYPTOPP_ASSERT
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:69
Name::BlockSize
const char * BlockSize()
int, in bytes
Definition: argnames.h:27
IteratedHashBase::OptimalBlockSize
unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this cipher.
Definition: iterhash.h:50
IteratedHashBase::OptimalDataAlignment
unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
Definition: iterhash.h:55
IteratedHashBase
Iterated hash base class.
Definition: iterhash.h:35
IteratedHashBase::AlgorithmProvider
virtual std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition: iterhash.h:91
IteratedHash
Iterated hash base class.
Definition: iterhash.h:123
CryptoPP
Crypto++ library namespace.
InvalidDataFormat
Input data was received that did not conform to expected format.
Definition: cryptlib.h:209