SHA256.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 tls.Crypto.Util.py3compat import bord
  21. from tls.Crypto.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. _raw_sha256_lib = load_pycryptodome_raw_lib("Crypto.Hash._SHA256",
  27. """
  28. int SHA256_init(void **shaState);
  29. int SHA256_destroy(void *shaState);
  30. int SHA256_update(void *hs,
  31. const uint8_t *buf,
  32. size_t len);
  33. int SHA256_digest(const void *shaState,
  34. uint8_t *digest,
  35. size_t digest_size);
  36. int SHA256_copy(const void *src, void *dst);
  37. int SHA256_pbkdf2_hmac_assist(const void *inner,
  38. const void *outer,
  39. const uint8_t *first_digest,
  40. uint8_t *final_digest,
  41. size_t iterations,
  42. size_t digest_size);
  43. """)
  44. class SHA256Hash(object):
  45. """A SHA-256 hash object.
  46. Do not instantiate directly. Use the :func:`new` function.
  47. :ivar oid: ASN.1 Object ID
  48. :vartype oid: string
  49. :ivar block_size: the size in bytes of the internal message block,
  50. input to the compression function
  51. :vartype block_size: integer
  52. :ivar digest_size: the size in bytes of the resulting hash
  53. :vartype digest_size: integer
  54. """
  55. # The size of the resulting hash in bytes.
  56. digest_size = 32
  57. # The internal block size of the hash algorithm in bytes.
  58. block_size = 64
  59. # ASN.1 Object ID
  60. oid = "2.16.840.1.101.3.4.2.1"
  61. def __init__(self, data=None):
  62. state = VoidPointer()
  63. result = _raw_sha256_lib.SHA256_init(state.address_of())
  64. if result:
  65. raise ValueError("Error %d while instantiating SHA256"
  66. % result)
  67. self._state = SmartPointer(state.get(),
  68. _raw_sha256_lib.SHA256_destroy)
  69. if data:
  70. self.update(data)
  71. def update(self, data):
  72. """Continue hashing of a message by consuming the next chunk of data.
  73. Args:
  74. data (byte string/byte array/memoryview): The next chunk of the message being hashed.
  75. """
  76. result = _raw_sha256_lib.SHA256_update(self._state.get(),
  77. c_uint8_ptr(data),
  78. c_size_t(len(data)))
  79. if result:
  80. raise ValueError("Error %d while hashing data with SHA256"
  81. % result)
  82. def digest(self):
  83. """Return the **binary** (non-printable) digest of the message that has been hashed so far.
  84. :return: The hash digest, computed over the data processed so far.
  85. Binary form.
  86. :rtype: byte string
  87. """
  88. bfr = create_string_buffer(self.digest_size)
  89. result = _raw_sha256_lib.SHA256_digest(self._state.get(),
  90. bfr,
  91. c_size_t(self.digest_size))
  92. if result:
  93. raise ValueError("Error %d while making SHA256 digest"
  94. % result)
  95. return get_raw_buffer(bfr)
  96. def hexdigest(self):
  97. """Return the **printable** digest of the message that has been hashed so far.
  98. :return: The hash digest, computed over the data processed so far.
  99. Hexadecimal encoded.
  100. :rtype: string
  101. """
  102. return "".join(["%02x" % bord(x) for x in self.digest()])
  103. def copy(self):
  104. """Return a copy ("clone") of the hash object.
  105. The copy will have the same internal state as the original hash
  106. object.
  107. This can be used to efficiently compute the digests of strings that
  108. share a common initial substring.
  109. :return: A hash object of the same type
  110. """
  111. clone = SHA256Hash()
  112. result = _raw_sha256_lib.SHA256_copy(self._state.get(),
  113. clone._state.get())
  114. if result:
  115. raise ValueError("Error %d while copying SHA256" % result)
  116. return clone
  117. def new(self, data=None):
  118. """Create a fresh SHA-256 hash object."""
  119. return SHA256Hash(data)
  120. def new(data=None):
  121. """Create a new hash object.
  122. :parameter data:
  123. Optional. The very first chunk of the message to hash.
  124. It is equivalent to an early call to :meth:`SHA256Hash.update`.
  125. :type data: byte string/byte array/memoryview
  126. :Return: A :class:`SHA256Hash` hash object
  127. """
  128. return SHA256Hash().new(data)
  129. # The size of the resulting hash in bytes.
  130. digest_size = SHA256Hash.digest_size
  131. # The internal block size of the hash algorithm in bytes.
  132. block_size = SHA256Hash.block_size
  133. def _pbkdf2_hmac_assist(inner, outer, first_digest, iterations):
  134. """Compute the expensive inner loop in PBKDF-HMAC."""
  135. assert iterations > 0
  136. bfr = create_string_buffer(len(first_digest));
  137. result = _raw_sha256_lib.SHA256_pbkdf2_hmac_assist(
  138. inner._state.get(),
  139. outer._state.get(),
  140. first_digest,
  141. bfr,
  142. c_size_t(iterations),
  143. c_size_t(len(first_digest)))
  144. if result:
  145. raise ValueError("Error %d with PBKDF2-HMAC assist for SHA256" % result)
  146. return get_raw_buffer(bfr)