KangarooTwelve.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2021, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. from Cryptodome.Util._raw_api import (VoidPointer, SmartPointer,
  31. create_string_buffer,
  32. get_raw_buffer, c_size_t,
  33. c_uint8_ptr, c_ubyte)
  34. from Cryptodome.Util.number import long_to_bytes
  35. from Cryptodome.Util.py3compat import bchr
  36. from .keccak import _raw_keccak_lib
  37. def _length_encode(x):
  38. if x == 0:
  39. return b'\x00'
  40. S = long_to_bytes(x)
  41. return S + bchr(len(S))
  42. # Possible states for a KangarooTwelve instance, which depend on the amount of data processed so far.
  43. SHORT_MSG = 1 # Still within the first 8192 bytes, but it is not certain we will exceed them.
  44. LONG_MSG_S0 = 2 # Still within the first 8192 bytes, and it is certain we will exceed them.
  45. LONG_MSG_SX = 3 # Beyond the first 8192 bytes.
  46. SQUEEZING = 4 # No more data to process.
  47. class K12_XOF(object):
  48. """A KangarooTwelve hash object.
  49. Do not instantiate directly.
  50. Use the :func:`new` function.
  51. """
  52. def __init__(self, data, custom):
  53. if custom == None:
  54. custom = b''
  55. self._custom = custom + _length_encode(len(custom))
  56. self._state = SHORT_MSG
  57. self._padding = None # Final padding is only decided in read()
  58. # Internal hash that consumes FinalNode
  59. self._hash1 = self._create_keccak()
  60. self._length1 = 0
  61. # Internal hash that produces CV_i (reset each time)
  62. self._hash2 = None
  63. self._length2 = 0
  64. # Incremented by one for each 8192-byte block
  65. self._ctr = 0
  66. if data:
  67. self.update(data)
  68. def _create_keccak(self):
  69. state = VoidPointer()
  70. result = _raw_keccak_lib.keccak_init(state.address_of(),
  71. c_size_t(32), # 32 bytes of capacity (256 bits)
  72. c_ubyte(12)) # Reduced number of rounds
  73. if result:
  74. raise ValueError("Error %d while instantiating KangarooTwelve"
  75. % result)
  76. return SmartPointer(state.get(), _raw_keccak_lib.keccak_destroy)
  77. def _update(self, data, hash_obj):
  78. result = _raw_keccak_lib.keccak_absorb(hash_obj.get(),
  79. c_uint8_ptr(data),
  80. c_size_t(len(data)))
  81. if result:
  82. raise ValueError("Error %d while updating KangarooTwelve state"
  83. % result)
  84. def _squeeze(self, hash_obj, length, padding):
  85. bfr = create_string_buffer(length)
  86. result = _raw_keccak_lib.keccak_squeeze(hash_obj.get(),
  87. bfr,
  88. c_size_t(length),
  89. c_ubyte(padding))
  90. if result:
  91. raise ValueError("Error %d while extracting from KangarooTwelve"
  92. % result)
  93. return get_raw_buffer(bfr)
  94. def _reset(self, hash_obj):
  95. result = _raw_keccak_lib.keccak_reset(hash_obj.get())
  96. if result:
  97. raise ValueError("Error %d while resetting KangarooTwelve state"
  98. % result)
  99. def update(self, data):
  100. """Hash the next piece of data.
  101. .. note::
  102. For better performance, submit chunks with a length multiple of 8192 bytes.
  103. Args:
  104. data (byte string/byte array/memoryview): The next chunk of the
  105. message to hash.
  106. """
  107. if self._state == SQUEEZING:
  108. raise TypeError("You cannot call 'update' after the first 'read'")
  109. if self._state == SHORT_MSG:
  110. next_length = self._length1 + len(data)
  111. if next_length + len(self._custom) <= 8192:
  112. self._length1 = next_length
  113. self._update(data, self._hash1)
  114. return self
  115. # Switch to tree hashing
  116. self._state = LONG_MSG_S0
  117. if self._state == LONG_MSG_S0:
  118. data_mem = memoryview(data)
  119. assert(self._length1 < 8192)
  120. dtc = min(len(data), 8192 - self._length1)
  121. self._update(data_mem[:dtc], self._hash1)
  122. self._length1 += dtc
  123. if self._length1 < 8192:
  124. return self
  125. # Finish hashing S_0 and start S_1
  126. assert(self._length1 == 8192)
  127. divider = b'\x03' + b'\x00' * 7
  128. self._update(divider, self._hash1)
  129. self._length1 += 8
  130. self._hash2 = self._create_keccak()
  131. self._length2 = 0
  132. self._ctr = 1
  133. self._state = LONG_MSG_SX
  134. return self.update(data_mem[dtc:])
  135. # LONG_MSG_SX
  136. assert(self._state == LONG_MSG_SX)
  137. index = 0
  138. len_data = len(data)
  139. # All iteractions could actually run in parallel
  140. data_mem = memoryview(data)
  141. while index < len_data:
  142. new_index = min(index + 8192 - self._length2, len_data)
  143. self._update(data_mem[index:new_index], self._hash2)
  144. self._length2 += new_index - index
  145. index = new_index
  146. if self._length2 == 8192:
  147. cv_i = self._squeeze(self._hash2, 32, 0x0B)
  148. self._update(cv_i, self._hash1)
  149. self._length1 += 32
  150. self._reset(self._hash2)
  151. self._length2 = 0
  152. self._ctr += 1
  153. return self
  154. def read(self, length):
  155. """
  156. Produce more bytes of the digest.
  157. .. note::
  158. You cannot use :meth:`update` anymore after the first call to
  159. :meth:`read`.
  160. Args:
  161. length (integer): the amount of bytes this method must return
  162. :return: the next piece of XOF output (of the given length)
  163. :rtype: byte string
  164. """
  165. custom_was_consumed = False
  166. if self._state == SHORT_MSG:
  167. self._update(self._custom, self._hash1)
  168. self._padding = 0x07
  169. self._state = SQUEEZING
  170. if self._state == LONG_MSG_S0:
  171. self.update(self._custom)
  172. custom_was_consumed = True
  173. assert(self._state == LONG_MSG_SX)
  174. if self._state == LONG_MSG_SX:
  175. if not custom_was_consumed:
  176. self.update(self._custom)
  177. # Is there still some leftover data in hash2?
  178. if self._length2 > 0:
  179. cv_i = self._squeeze(self._hash2, 32, 0x0B)
  180. self._update(cv_i, self._hash1)
  181. self._length1 += 32
  182. self._reset(self._hash2)
  183. self._length2 = 0
  184. self._ctr += 1
  185. trailer = _length_encode(self._ctr - 1) + b'\xFF\xFF'
  186. self._update(trailer, self._hash1)
  187. self._padding = 0x06
  188. self._state = SQUEEZING
  189. return self._squeeze(self._hash1, length, self._padding)
  190. def new(self, data=None, custom=b''):
  191. return type(self)(data, custom)
  192. def new(data=None, custom=None):
  193. """Return a fresh instance of a KangarooTwelve object.
  194. Args:
  195. data (bytes/bytearray/memoryview):
  196. Optional.
  197. The very first chunk of the message to hash.
  198. It is equivalent to an early call to :meth:`update`.
  199. custom (bytes):
  200. Optional.
  201. A customization byte string.
  202. :Return: A :class:`K12_XOF` object
  203. """
  204. return K12_XOF(data, custom)