KangarooTwelve.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. import os
  31. import threading
  32. from Crypto.Util.number import long_to_bytes
  33. from Crypto.Util.py3compat import bchr, is_native_int
  34. from Crypto.Util._raw_api import c_size_t, c_uint8_ptr
  35. from . import TurboSHAKE128
  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. def _hash_leaves(leaves, cvs):
  43. """Compute the chaining values of complete 8192-byte leaves.
  44. The C function does not use any shared state, so different ranges
  45. of leaves can be processed concurrently, each one into its own
  46. slice of a common CV buffer.
  47. Args:
  48. leaves (memoryview): ``n`` leaves, ``8192 * n`` bytes
  49. cvs (memoryview): writeable output buffer, ``32 * n`` bytes
  50. """
  51. n_leaves = len(leaves) // 8192
  52. assert len(leaves) == 8192 * n_leaves
  53. assert len(cvs) == 32 * n_leaves
  54. if n_leaves == 0:
  55. return
  56. result = _raw_keccak_lib.k12_leaves(c_uint8_ptr(leaves),
  57. c_size_t(n_leaves),
  58. c_uint8_ptr(cvs))
  59. if result:
  60. raise ValueError("Error %d while hashing K12 leaves" % result)
  61. # Minimum amount of whole leaves (256 KiB) that each thread must hash:
  62. # with less, starting the thread costs more than what it saves.
  63. _MIN_LEAVES_PER_THREAD = 32
  64. def _available_cores():
  65. """Return the number of CPU cores this process can run on."""
  66. # Python 3.13+: it takes into account CPU affinity and -X cpu_count
  67. if hasattr(os, "process_cpu_count"):
  68. count = os.process_cpu_count()
  69. elif hasattr(os, "sched_getaffinity"):
  70. count = len(os.sched_getaffinity(0))
  71. elif hasattr(os, "cpu_count"):
  72. count = os.cpu_count()
  73. else:
  74. import multiprocessing
  75. try:
  76. count = multiprocessing.cpu_count()
  77. except NotImplementedError:
  78. count = None
  79. return count or 1
  80. def _hash_leaves_threaded(leaves, cvs, threads):
  81. """Like :func:`_hash_leaves`, but split the leaves into ``threads``
  82. contiguous ranges, which are processed in parallel.
  83. Fewer threads are used if a range would be shorter than
  84. ``_MIN_LEAVES_PER_THREAD`` leaves.
  85. The calling thread processes the first range.
  86. """
  87. n_leaves = len(leaves) // 8192
  88. threads = min(threads, n_leaves // _MIN_LEAVES_PER_THREAD)
  89. if threads <= 1:
  90. _hash_leaves(leaves, cvs)
  91. return
  92. errors = []
  93. def worker(start, end):
  94. try:
  95. _hash_leaves(leaves[8192 * start:8192 * end],
  96. cvs[32 * start:32 * end])
  97. except Exception as e:
  98. errors.append(e)
  99. # Ranges differ by at most one leaf
  100. bounds = [n_leaves * i // threads for i in range(threads + 1)]
  101. workers = []
  102. for i in range(1, threads):
  103. t = threading.Thread(target=worker, args=(bounds[i], bounds[i + 1]))
  104. t.daemon = True
  105. t.start()
  106. workers.append(t)
  107. worker(bounds[0], bounds[1])
  108. for t in workers:
  109. t.join()
  110. if errors:
  111. raise errors[0]
  112. # Possible states for a KangarooTwelve instance, which depend on the amount of data processed so far.
  113. SHORT_MSG = 1 # Still within the first 8192 bytes, but it is not certain we will exceed them.
  114. LONG_MSG_S0 = 2 # Still within the first 8192 bytes, and it is certain we will exceed them.
  115. LONG_MSG_SX = 3 # Beyond the first 8192 bytes.
  116. SQUEEZING = 4 # No more data to process.
  117. class K12_XOF(object):
  118. """A KangarooTwelve hash object.
  119. Do not instantiate directly.
  120. Use the :func:`new` function.
  121. """
  122. def __init__(self, data, custom, threads=1):
  123. if custom == None:
  124. custom = b''
  125. if not is_native_int(threads) or isinstance(threads, bool):
  126. raise TypeError("'threads' must be an integer")
  127. if threads < 0:
  128. raise ValueError("'threads' must be a non-negative integer")
  129. if threads == 0:
  130. threads = _available_cores()
  131. self._threads = threads
  132. self._custom = custom + _length_encode(len(custom))
  133. self._state = SHORT_MSG
  134. self._padding = None # Final padding is only decided in read()
  135. # Internal hash that consumes FinalNode
  136. # The real domain separation byte will be known before squeezing
  137. self._hash1 = TurboSHAKE128.new(domain=1)
  138. self._length1 = 0
  139. # Internal hash that produces CV_i (reset each time)
  140. self._hash2 = None
  141. self._length2 = 0
  142. # Incremented by one for each 8192-byte block
  143. self._ctr = 0
  144. if data:
  145. self.update(data)
  146. def update(self, data):
  147. """Hash the next piece of data.
  148. .. note::
  149. For better performance, submit chunks with a length multiple of 8192 bytes.
  150. Args:
  151. data (byte string/byte array/memoryview): The next chunk of the
  152. message to hash.
  153. """
  154. if self._state == SQUEEZING:
  155. raise TypeError("You cannot call 'update' after the first 'read'")
  156. if self._state == SHORT_MSG:
  157. next_length = self._length1 + len(data)
  158. if next_length + len(self._custom) <= 8192:
  159. self._length1 = next_length
  160. self._hash1.update(data)
  161. return self
  162. # Switch to tree hashing
  163. self._state = LONG_MSG_S0
  164. if self._state == LONG_MSG_S0:
  165. data_mem = memoryview(data)
  166. assert(self._length1 < 8192)
  167. dtc = min(len(data), 8192 - self._length1)
  168. self._hash1.update(data_mem[:dtc])
  169. self._length1 += dtc
  170. if self._length1 < 8192:
  171. return self
  172. # Finish hashing S_0 and start S_1
  173. assert(self._length1 == 8192)
  174. divider = b'\x03' + b'\x00' * 7
  175. self._hash1.update(divider)
  176. self._length1 += 8
  177. self._hash2 = TurboSHAKE128.new(domain=0x0B)
  178. self._length2 = 0
  179. self._ctr = 1
  180. self._state = LONG_MSG_SX
  181. return self.update(data_mem[dtc:])
  182. # LONG_MSG_SX
  183. assert(self._state == LONG_MSG_SX)
  184. index = 0
  185. len_data = len(data)
  186. # All iteractions could actually run in parallel
  187. data_mem = memoryview(data)
  188. while index < len_data:
  189. if self._length2 == 0 and len_data - index >= 8192:
  190. index = self._update_full_leaves(data_mem, index)
  191. continue
  192. new_index = min(index + 8192 - self._length2, len_data)
  193. self._hash2.update(data_mem[index:new_index])
  194. self._length2 += new_index - index
  195. index = new_index
  196. if self._length2 == 8192:
  197. cv_i = self._hash2.read(32)
  198. self._hash1.update(cv_i)
  199. self._length1 += 32
  200. self._hash2._reset()
  201. self._length2 = 0
  202. self._ctr += 1
  203. return self
  204. def _update_full_leaves(self, data_mem, index):
  205. """Hash as many complete 8192-byte leaves as available,
  206. starting at offset ``index`` of ``data_mem``.
  207. This is the hot path for long messages: all leaves are hashed
  208. with a single call to the raw Keccak library.
  209. :return: the offset of the first byte not consumed
  210. """
  211. assert self._length2 == 0
  212. n_leaves = (len(data_mem) - index) // 8192
  213. end = index + 8192 * n_leaves
  214. cvs = bytearray(32 * n_leaves)
  215. if self._threads > 1:
  216. _hash_leaves_threaded(data_mem[index:end], memoryview(cvs),
  217. self._threads)
  218. else:
  219. _hash_leaves(data_mem[index:end], memoryview(cvs))
  220. self._hash1.update(cvs)
  221. self._length1 += 32 * n_leaves
  222. self._ctr += n_leaves
  223. return end
  224. def read(self, length):
  225. """
  226. Produce more bytes of the digest.
  227. .. note::
  228. You cannot use :meth:`update` anymore after the first call to
  229. :meth:`read`.
  230. Args:
  231. length (integer): the amount of bytes this method must return
  232. :return: the next piece of XOF output (of the given length)
  233. :rtype: byte string
  234. """
  235. custom_was_consumed = False
  236. # The message and the customization string together may still
  237. # exceed 8192 bytes, if update() was never called
  238. if self._state == SHORT_MSG and \
  239. self._length1 + len(self._custom) > 8192:
  240. self._state = LONG_MSG_S0
  241. if self._state == SHORT_MSG:
  242. self._hash1.update(self._custom)
  243. self._padding = 0x07
  244. self._state = SQUEEZING
  245. if self._state == LONG_MSG_S0:
  246. self.update(self._custom)
  247. custom_was_consumed = True
  248. assert(self._state == LONG_MSG_SX)
  249. if self._state == LONG_MSG_SX:
  250. if not custom_was_consumed:
  251. self.update(self._custom)
  252. # Is there still some leftover data in hash2?
  253. if self._length2 > 0:
  254. cv_i = self._hash2.read(32)
  255. self._hash1.update(cv_i)
  256. self._length1 += 32
  257. self._hash2._reset()
  258. self._length2 = 0
  259. self._ctr += 1
  260. trailer = _length_encode(self._ctr - 1) + b'\xFF\xFF'
  261. self._hash1.update(trailer)
  262. self._padding = 0x06
  263. self._state = SQUEEZING
  264. self._hash1._domain = self._padding
  265. return self._hash1.read(length)
  266. def new(self, data=None, custom=b'', threads=1):
  267. return type(self)(data, custom, threads)
  268. def new(data=None, custom=None, threads=1):
  269. """Return a fresh instance of a KangarooTwelve object.
  270. Args:
  271. data (bytes/bytearray/memoryview):
  272. Optional.
  273. The very first chunk of the message to hash.
  274. It is equivalent to an early call to :meth:`update`.
  275. custom (bytes):
  276. Optional.
  277. A customization byte string.
  278. threads (integer):
  279. Optional.
  280. The maximum number of threads used to hash long messages
  281. (default: 1, no extra threads).
  282. Use 0 for as many threads as the CPU cores available
  283. to this process.
  284. Each thread hashes at least 256 KiB of a single call to
  285. :meth:`K12_XOF.update` (or of ``data``): with shorter
  286. inputs, fewer threads are used, or none at all.
  287. For best results, do not exceed the number of physical cores.
  288. The output does not depend on the number of threads.
  289. :Return: A :class:`K12_XOF` object
  290. """
  291. return K12_XOF(data, custom, threads)