SHA224.py 6.7 KB

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