keccak.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 tls.Crypto.Util.py3compat import bord
  31. from tls.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)
  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/byte array/memoryview): 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. result = _raw_keccak_lib.keccak_absorb(self._state.get(),
  80. c_uint8_ptr(data),
  81. c_size_t(len(data)))
  82. if result:
  83. raise ValueError("Error %d while updating keccak" % result)
  84. return self
  85. def digest(self):
  86. """Return the **binary** (non-printable) digest of the message that has been hashed so far.
  87. :return: The hash digest, computed over the data processed so far.
  88. Binary form.
  89. :rtype: byte string
  90. """
  91. self._digest_done = True
  92. bfr = create_string_buffer(self.digest_size)
  93. result = _raw_keccak_lib.keccak_digest(self._state.get(),
  94. bfr,
  95. c_size_t(self.digest_size))
  96. if result:
  97. raise ValueError("Error %d while squeezing keccak" % result)
  98. return get_raw_buffer(bfr)
  99. def hexdigest(self):
  100. """Return the **printable** digest of the message that has been hashed so far.
  101. :return: The hash digest, computed over the data processed so far.
  102. Hexadecimal encoded.
  103. :rtype: string
  104. """
  105. return "".join(["%02x" % bord(x) for x in self.digest()])
  106. def new(self, **kwargs):
  107. """Create a fresh Keccak hash object."""
  108. if "digest_bytes" not in kwargs and "digest_bits" not in kwargs:
  109. kwargs["digest_bytes"] = self.digest_size
  110. return new(**kwargs)
  111. def new(**kwargs):
  112. """Create a new hash object.
  113. Args:
  114. data (bytes/bytearray/memoryview):
  115. The very first chunk of the message to hash.
  116. It is equivalent to an early call to :meth:`Keccak_Hash.update`.
  117. digest_bytes (integer):
  118. The size of the digest, in bytes (28, 32, 48, 64).
  119. digest_bits (integer):
  120. The size of the digest, in bits (224, 256, 384, 512).
  121. update_after_digest (boolean):
  122. Whether :meth:`Keccak.digest` can be followed by another
  123. :meth:`Keccak.update` (default: ``False``).
  124. :Return: A :class:`Keccak_Hash` hash object
  125. """
  126. data = kwargs.pop("data", None)
  127. update_after_digest = kwargs.pop("update_after_digest", False)
  128. digest_bytes = kwargs.pop("digest_bytes", None)
  129. digest_bits = kwargs.pop("digest_bits", None)
  130. if None not in (digest_bytes, digest_bits):
  131. raise TypeError("Only one digest parameter must be provided")
  132. if (None, None) == (digest_bytes, digest_bits):
  133. raise TypeError("Digest size (bits, bytes) not provided")
  134. if digest_bytes is not None:
  135. if digest_bytes not in (28, 32, 48, 64):
  136. raise ValueError("'digest_bytes' must be: 28, 32, 48 or 64")
  137. else:
  138. if digest_bits not in (224, 256, 384, 512):
  139. raise ValueError("'digest_bytes' must be: 224, 256, 384 or 512")
  140. digest_bytes = digest_bits // 8
  141. if kwargs:
  142. raise TypeError("Unknown parameters: " + str(kwargs))
  143. return Keccak_Hash(data, digest_bytes, update_after_digest)