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