keccak.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2015, 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 Crypto.Util.py3compat import bord
  31. from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  32. VoidPointer, SmartPointer,
  33. create_string_buffer,
  34. get_raw_buffer, c_size_t,
  35. c_uint8_ptr, c_ubyte)
  36. _raw_keccak_lib = load_pycryptodome_raw_lib("Crypto.Hash._keccak",
  37. """
  38. int keccak_init(void **state,
  39. size_t capacity_bytes,
  40. uint8_t rounds);
  41. int keccak_destroy(void *state);
  42. int keccak_absorb(void *state,
  43. const uint8_t *in,
  44. size_t len);
  45. int keccak_squeeze(const void *state,
  46. uint8_t *out,
  47. size_t len,
  48. uint8_t padding);
  49. int keccak_digest(void *state,
  50. uint8_t *digest,
  51. size_t len,
  52. uint8_t padding);
  53. int keccak_copy(const void *src, void *dst);
  54. int keccak_reset(void *state);
  55. int k12_leaves(const uint8_t *in,
  56. size_t n_leaves,
  57. uint8_t *cvs);
  58. """)
  59. class Keccak_Hash(object):
  60. """A Keccak hash object.
  61. Do not instantiate directly.
  62. Use the :func:`new` function.
  63. :ivar digest_size: the size in bytes of the resulting hash
  64. :vartype digest_size: integer
  65. """
  66. def __init__(self, data, digest_bytes, update_after_digest):
  67. # The size of the resulting hash in bytes.
  68. self.digest_size = digest_bytes
  69. self._update_after_digest = update_after_digest
  70. self._digest_done = False
  71. self._padding = 0x01
  72. state = VoidPointer()
  73. result = _raw_keccak_lib.keccak_init(state.address_of(),
  74. c_size_t(self.digest_size * 2),
  75. c_ubyte(24))
  76. if result:
  77. raise ValueError("Error %d while instantiating keccak" % result)
  78. self._state = SmartPointer(state.get(),
  79. _raw_keccak_lib.keccak_destroy)
  80. if data:
  81. self.update(data)
  82. def update(self, data):
  83. """Continue hashing of a message by consuming the next chunk of data.
  84. Args:
  85. data (byte string/byte array/memoryview): The next chunk of the message being hashed.
  86. """
  87. if self._digest_done and not self._update_after_digest:
  88. raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
  89. result = _raw_keccak_lib.keccak_absorb(self._state.get(),
  90. c_uint8_ptr(data),
  91. c_size_t(len(data)))
  92. if result:
  93. raise ValueError("Error %d while updating keccak" % result)
  94. return self
  95. def digest(self):
  96. """Return the **binary** (non-printable) digest of the message that has been hashed so far.
  97. :return: The hash digest, computed over the data processed so far.
  98. Binary form.
  99. :rtype: byte string
  100. """
  101. self._digest_done = True
  102. bfr = create_string_buffer(self.digest_size)
  103. result = _raw_keccak_lib.keccak_digest(self._state.get(),
  104. bfr,
  105. c_size_t(self.digest_size),
  106. c_ubyte(self._padding))
  107. if result:
  108. raise ValueError("Error %d while squeezing keccak" % result)
  109. return get_raw_buffer(bfr)
  110. def hexdigest(self):
  111. """Return the **printable** digest of the message that has been hashed so far.
  112. :return: The hash digest, computed over the data processed so far.
  113. Hexadecimal encoded.
  114. :rtype: string
  115. """
  116. return "".join(["%02x" % bord(x) for x in self.digest()])
  117. def new(self, **kwargs):
  118. """Create a fresh Keccak hash object."""
  119. if "digest_bytes" not in kwargs and "digest_bits" not in kwargs:
  120. kwargs["digest_bytes"] = self.digest_size
  121. return new(**kwargs)
  122. def new(**kwargs):
  123. """Create a new hash object.
  124. Args:
  125. data (bytes/bytearray/memoryview):
  126. The very first chunk of the message to hash.
  127. It is equivalent to an early call to :meth:`Keccak_Hash.update`.
  128. digest_bytes (integer):
  129. The size of the digest, in bytes (28, 32, 48, 64).
  130. digest_bits (integer):
  131. The size of the digest, in bits (224, 256, 384, 512).
  132. update_after_digest (boolean):
  133. Whether :meth:`Keccak.digest` can be followed by another
  134. :meth:`Keccak.update` (default: ``False``).
  135. :Return: A :class:`Keccak_Hash` hash object
  136. """
  137. data = kwargs.pop("data", None)
  138. update_after_digest = kwargs.pop("update_after_digest", False)
  139. digest_bytes = kwargs.pop("digest_bytes", None)
  140. digest_bits = kwargs.pop("digest_bits", None)
  141. if None not in (digest_bytes, digest_bits):
  142. raise TypeError("Only one digest parameter must be provided")
  143. if (None, None) == (digest_bytes, digest_bits):
  144. raise TypeError("Digest size (bits, bytes) not provided")
  145. if digest_bytes is not None:
  146. if digest_bytes not in (28, 32, 48, 64):
  147. raise ValueError("'digest_bytes' must be: 28, 32, 48 or 64")
  148. else:
  149. if digest_bits not in (224, 256, 384, 512):
  150. raise ValueError("'digest_bytes' must be: 224, 256, 384 or 512")
  151. digest_bytes = digest_bits // 8
  152. if kwargs:
  153. raise TypeError("Unknown parameters: " + str(kwargs))
  154. return Keccak_Hash(data, digest_bytes, update_after_digest)