keccak.py 6.9 KB

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