BLAKE2b.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, 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 binascii import unhexlify
  31. from tls.Crypto.Util.py3compat import bord, tobytes
  32. from tls.Crypto.Random import get_random_bytes
  33. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  34. VoidPointer, SmartPointer,
  35. create_string_buffer,
  36. get_raw_buffer, c_size_t,
  37. c_uint8_ptr)
  38. _raw_blake2b_lib = load_pycryptodome_raw_lib("Crypto.Hash._BLAKE2b",
  39. """
  40. int blake2b_init(void **state,
  41. const uint8_t *key,
  42. size_t key_size,
  43. size_t digest_size);
  44. int blake2b_destroy(void *state);
  45. int blake2b_update(void *state,
  46. const uint8_t *buf,
  47. size_t len);
  48. int blake2b_digest(const void *state,
  49. uint8_t digest[64]);
  50. int blake2b_copy(const void *src, void *dst);
  51. """)
  52. class BLAKE2b_Hash(object):
  53. """A BLAKE2b hash object.
  54. Do not instantiate directly. Use the :func:`new` function.
  55. :ivar oid: ASN.1 Object ID
  56. :vartype oid: string
  57. :ivar block_size: the size in bytes of the internal message block,
  58. input to the compression function
  59. :vartype block_size: integer
  60. :ivar digest_size: the size in bytes of the resulting hash
  61. :vartype digest_size: integer
  62. """
  63. # The internal block size of the hash algorithm in bytes.
  64. block_size = 64
  65. def __init__(self, data, key, digest_bytes, update_after_digest):
  66. # The size of the resulting hash in bytes.
  67. self.digest_size = digest_bytes
  68. self._update_after_digest = update_after_digest
  69. self._digest_done = False
  70. # See https://tools.ietf.org/html/rfc7693
  71. if digest_bytes in (20, 32, 48, 64) and not key:
  72. self.oid = "1.3.6.1.4.1.1722.12.2.1." + str(digest_bytes)
  73. state = VoidPointer()
  74. result = _raw_blake2b_lib.blake2b_init(state.address_of(),
  75. c_uint8_ptr(key),
  76. c_size_t(len(key)),
  77. c_size_t(digest_bytes)
  78. )
  79. if result:
  80. raise ValueError("Error %d while instantiating BLAKE2b" % result)
  81. self._state = SmartPointer(state.get(),
  82. _raw_blake2b_lib.blake2b_destroy)
  83. if data:
  84. self.update(data)
  85. def update(self, data):
  86. """Continue hashing of a message by consuming the next chunk of data.
  87. Args:
  88. data (bytes/bytearray/memoryview): The next chunk of the message being hashed.
  89. """
  90. if self._digest_done and not self._update_after_digest:
  91. raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
  92. result = _raw_blake2b_lib.blake2b_update(self._state.get(),
  93. c_uint8_ptr(data),
  94. c_size_t(len(data)))
  95. if result:
  96. raise ValueError("Error %d while hashing BLAKE2b data" % result)
  97. return self
  98. def digest(self):
  99. """Return the **binary** (non-printable) digest of the message that has been hashed so far.
  100. :return: The hash digest, computed over the data processed so far.
  101. Binary form.
  102. :rtype: byte string
  103. """
  104. bfr = create_string_buffer(64)
  105. result = _raw_blake2b_lib.blake2b_digest(self._state.get(),
  106. bfr)
  107. if result:
  108. raise ValueError("Error %d while creating BLAKE2b digest" % result)
  109. self._digest_done = True
  110. return get_raw_buffer(bfr)[:self.digest_size]
  111. def hexdigest(self):
  112. """Return the **printable** digest of the message that has been hashed so far.
  113. :return: The hash digest, computed over the data processed so far.
  114. Hexadecimal encoded.
  115. :rtype: string
  116. """
  117. return "".join(["%02x" % bord(x) for x in tuple(self.digest())])
  118. def verify(self, mac_tag):
  119. """Verify that a given **binary** MAC (computed by another party)
  120. is valid.
  121. Args:
  122. mac_tag (bytes/bytearray/memoryview): the expected MAC of the message.
  123. Raises:
  124. ValueError: if the MAC does not match. It means that the message
  125. has been tampered with or that the MAC key is incorrect.
  126. """
  127. secret = get_random_bytes(16)
  128. mac1 = new(digest_bits=160, key=secret, data=mac_tag)
  129. mac2 = new(digest_bits=160, key=secret, data=self.digest())
  130. if mac1.digest() != mac2.digest():
  131. raise ValueError("MAC check failed")
  132. def hexverify(self, hex_mac_tag):
  133. """Verify that a given **printable** MAC (computed by another party)
  134. is valid.
  135. Args:
  136. hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string.
  137. Raises:
  138. ValueError: if the MAC does not match. It means that the message
  139. has been tampered with or that the MAC key is incorrect.
  140. """
  141. self.verify(unhexlify(tobytes(hex_mac_tag)))
  142. def new(self, **kwargs):
  143. """Return a new instance of a BLAKE2b hash object.
  144. See :func:`new`.
  145. """
  146. if "digest_bytes" not in kwargs and "digest_bits" not in kwargs:
  147. kwargs["digest_bytes"] = self.digest_size
  148. return new(**kwargs)
  149. def new(**kwargs):
  150. """Create a new hash object.
  151. Args:
  152. data (bytes/bytearray/memoryview):
  153. Optional. The very first chunk of the message to hash.
  154. It is equivalent to an early call to :meth:`BLAKE2b_Hash.update`.
  155. digest_bytes (integer):
  156. Optional. The size of the digest, in bytes (1 to 64). Default is 64.
  157. digest_bits (integer):
  158. Optional and alternative to ``digest_bytes``.
  159. The size of the digest, in bits (8 to 512, in steps of 8).
  160. Default is 512.
  161. key (bytes/bytearray/memoryview):
  162. Optional. The key to use to compute the MAC (1 to 64 bytes).
  163. If not specified, no key will be used.
  164. update_after_digest (boolean):
  165. Optional. By default, a hash object cannot be updated anymore after
  166. the digest is computed. When this flag is ``True``, such check
  167. is no longer enforced.
  168. Returns:
  169. A :class:`BLAKE2b_Hash` hash object
  170. """
  171. data = kwargs.pop("data", None)
  172. update_after_digest = kwargs.pop("update_after_digest", False)
  173. digest_bytes = kwargs.pop("digest_bytes", None)
  174. digest_bits = kwargs.pop("digest_bits", None)
  175. if None not in (digest_bytes, digest_bits):
  176. raise TypeError("Only one digest parameter must be provided")
  177. if (None, None) == (digest_bytes, digest_bits):
  178. digest_bytes = 64
  179. if digest_bytes is not None:
  180. if not (1 <= digest_bytes <= 64):
  181. raise ValueError("'digest_bytes' not in range 1..64")
  182. else:
  183. if not (8 <= digest_bits <= 512) or (digest_bits % 8):
  184. raise ValueError("'digest_bytes' not in range 8..512, "
  185. "with steps of 8")
  186. digest_bytes = digest_bits // 8
  187. key = kwargs.pop("key", b"")
  188. if len(key) > 64:
  189. raise ValueError("BLAKE2s key cannot exceed 64 bytes")
  190. if kwargs:
  191. raise TypeError("Unknown parameters: " + str(kwargs))
  192. return BLAKE2b_Hash(data, key, digest_bytes, update_after_digest)