iterhash.h 8.7 KB

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