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