keccak.py 7.4 KB

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