SHA3_384.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # -*- coding: utf-8 -*-
  2. #
  3. # ===================================================================
  4. # The contents of this file are dedicated to the public domain. To
  5. # the extent that dedication to the public domain is not available,
  6. # everyone is granted a worldwide, perpetual, royalty-free,
  7. # non-exclusive license to exercise all rights associated with the
  8. # contents of this file for any purpose whatsoever.
  9. # No rights are reserved.
  10. #
  11. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  12. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  14. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  15. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  16. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. # SOFTWARE.
  19. # ===================================================================
  20. from Cryptodome.Util.py3compat import bord
  21. from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib,
  22. VoidPointer, SmartPointer,
  23. create_string_buffer,
  24. get_raw_buffer, c_size_t,
  25. c_uint8_ptr)
  26. from Cryptodome.Hash.keccak import _raw_keccak_lib
  27. class SHA3_384_Hash(object):
  28. """A SHA3-384 hash object.
  29. Do not instantiate directly.
  30. Use the :func:`new` function.
  31. :ivar oid: ASN.1 Object ID
  32. :vartype oid: string
  33. :ivar digest_size: the size in bytes of the resulting hash
  34. :vartype digest_size: integer
  35. """
  36. # The size of the resulting hash in bytes.
  37. digest_size = 48
  38. # ASN.1 Object ID
  39. oid = "2.16.840.1.101.3.4.2.9"
  40. # Input block size for HMAC
  41. block_size = 104
  42. def __init__(self, data, update_after_digest):
  43. self._update_after_digest = update_after_digest
  44. self._digest_done = False
  45. state = VoidPointer()
  46. result = _raw_keccak_lib.keccak_init(state.address_of(),
  47. c_size_t(self.digest_size * 2),
  48. 0x06)
  49. if result:
  50. raise ValueError("Error %d while instantiating SHA-3/384"
  51. % result)
  52. self._state = SmartPointer(state.get(),
  53. _raw_keccak_lib.keccak_destroy)
  54. if data:
  55. self.update(data)
  56. def update(self, data):
  57. """Continue hashing of a message by consuming the next chunk of data.
  58. Args:
  59. data (byte string/byte array/memoryview): The next chunk of the message being hashed.
  60. """
  61. if self._digest_done and not self._update_after_digest:
  62. raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
  63. result = _raw_keccak_lib.keccak_absorb(self._state.get(),
  64. c_uint8_ptr(data),
  65. c_size_t(len(data)))
  66. if result:
  67. raise ValueError("Error %d while updating SHA-3/384"
  68. % result)
  69. return self
  70. def digest(self):
  71. """Return the **binary** (non-printable) digest of the message that has been hashed so far.
  72. :return: The hash digest, computed over the data processed so far.
  73. Binary form.
  74. :rtype: byte string
  75. """
  76. self._digest_done = True
  77. bfr = create_string_buffer(self.digest_size)
  78. result = _raw_keccak_lib.keccak_digest(self._state.get(),
  79. bfr,
  80. c_size_t(self.digest_size))
  81. if result:
  82. raise ValueError("Error %d while instantiating SHA-3/384"
  83. % result)
  84. self._digest_value = get_raw_buffer(bfr)
  85. return self._digest_value
  86. def hexdigest(self):
  87. """Return the **printable** digest of the message that has been hashed so far.
  88. :return: The hash digest, computed over the data processed so far.
  89. Hexadecimal encoded.
  90. :rtype: string
  91. """
  92. return "".join(["%02x" % bord(x) for x in self.digest()])
  93. def copy(self):
  94. """Return a copy ("clone") of the hash object.
  95. The copy will have the same internal state as the original hash
  96. object.
  97. This can be used to efficiently compute the digests of strings that
  98. share a common initial substring.
  99. :return: A hash object of the same type
  100. """
  101. clone = self.new()
  102. result = _raw_keccak_lib.keccak_copy(self._state.get(),
  103. clone._state.get())
  104. if result:
  105. raise ValueError("Error %d while copying SHA3-384" % result)
  106. return clone
  107. def new(self, data=None):
  108. """Create a fresh SHA3-256 hash object."""
  109. return type(self)(data, self._update_after_digest)
  110. def new(self, data=None):
  111. """Create a fresh SHA3-384 hash object."""
  112. return type(self)(data, self._update_after_digest)
  113. def new(*args, **kwargs):
  114. """Create a new hash object.
  115. Args:
  116. data (byte string/byte array/memoryview):
  117. The very first chunk of the message to hash.
  118. It is equivalent to an early call to :meth:`update`.
  119. update_after_digest (boolean):
  120. Whether :meth:`digest` can be followed by another :meth:`update`
  121. (default: ``False``).
  122. :Return: A :class:`SHA3_384_Hash` hash object
  123. """
  124. data = kwargs.pop("data", None)
  125. update_after_digest = kwargs.pop("update_after_digest", False)
  126. if len(args) == 1:
  127. if data:
  128. raise ValueError("Initial data for hash specified twice")
  129. data = args[0]
  130. if kwargs:
  131. raise TypeError("Unknown parameters: " + str(kwargs))
  132. return SHA3_384_Hash(data, update_after_digest)
  133. # The size of the resulting hash in bytes.
  134. digest_size = SHA3_384_Hash.digest_size
  135. # Input block size for HMAC
  136. block_size = 104