SHA1.py 6.5 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 *
  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_sha1_lib = load_pycryptodome_raw_lib("Crypto.Hash._SHA1",
  27. """
  28. #define SHA1_DIGEST_SIZE 20
  29. int SHA1_init(void **shaState);
  30. int SHA1_destroy(void *shaState);
  31. int SHA1_update(void *hs,
  32. const uint8_t *buf,
  33. size_t len);
  34. int SHA1_digest(const void *shaState,
  35. uint8_t digest[SHA1_DIGEST_SIZE]);
  36. int SHA1_copy(const void *src, void *dst);
  37. int SHA1_pbkdf2_hmac_assist(const void *inner,
  38. const void *outer,
  39. const uint8_t first_digest[SHA1_DIGEST_SIZE],
  40. uint8_t final_digest[SHA1_DIGEST_SIZE],
  41. size_t iterations);
  42. """)
  43. class SHA1Hash(object):
  44. """A SHA-1 hash object.
  45. Do not instantiate directly.
  46. 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 = 20
  57. # The internal block size of the hash algorithm in bytes.
  58. block_size = 64
  59. # ASN.1 Object ID
  60. oid = "1.3.14.3.2.26"
  61. def __init__(self, data=None):
  62. state = VoidPointer()
  63. result = _raw_sha1_lib.SHA1_init(state.address_of())
  64. if result:
  65. raise ValueError("Error %d while instantiating SHA1"
  66. % result)
  67. self._state = SmartPointer(state.get(),
  68. _raw_sha1_lib.SHA1_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_sha1_lib.SHA1_update(self._state.get(),
  77. c_uint8_ptr(data),
  78. c_size_t(len(data)))
  79. if result:
  80. raise ValueError("Error %d while instantiating SHA1"
  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_sha1_lib.SHA1_digest(self._state.get(),
  90. bfr)
  91. if result:
  92. raise ValueError("Error %d while instantiating SHA1"
  93. % result)
  94. return get_raw_buffer(bfr)
  95. def hexdigest(self):
  96. """Return the **printable** digest of the message that has been hashed so far.
  97. :return: The hash digest, computed over the data processed so far.
  98. Hexadecimal encoded.
  99. :rtype: string
  100. """
  101. return "".join(["%02x" % bord(x) for x in self.digest()])
  102. def copy(self):
  103. """Return a copy ("clone") of the hash object.
  104. The copy will have the same internal state as the original hash
  105. object.
  106. This can be used to efficiently compute the digests of strings that
  107. share a common initial substring.
  108. :return: A hash object of the same type
  109. """
  110. clone = SHA1Hash()
  111. result = _raw_sha1_lib.SHA1_copy(self._state.get(),
  112. clone._state.get())
  113. if result:
  114. raise ValueError("Error %d while copying SHA1" % result)
  115. return clone
  116. def new(self, data=None):
  117. """Create a fresh SHA-1 hash object."""
  118. return SHA1Hash(data)
  119. def new(data=None):
  120. """Create a new hash object.
  121. :parameter data:
  122. Optional. The very first chunk of the message to hash.
  123. It is equivalent to an early call to :meth:`SHA1Hash.update`.
  124. :type data: byte string/byte array/memoryview
  125. :Return: A :class:`SHA1Hash` hash object
  126. """
  127. return SHA1Hash().new(data)
  128. # The size of the resulting hash in bytes.
  129. digest_size = SHA1Hash.digest_size
  130. # The internal block size of the hash algorithm in bytes.
  131. block_size = SHA1Hash.block_size
  132. def _pbkdf2_hmac_assist(inner, outer, first_digest, iterations):
  133. """Compute the expensive inner loop in PBKDF-HMAC."""
  134. assert len(first_digest) == digest_size
  135. assert iterations > 0
  136. bfr = create_string_buffer(digest_size);
  137. result = _raw_sha1_lib.SHA1_pbkdf2_hmac_assist(
  138. inner._state.get(),
  139. outer._state.get(),
  140. first_digest,
  141. bfr,
  142. c_size_t(iterations))
  143. if result:
  144. raise ValueError("Error %d with PBKDF2-HMAC assis for SHA1" % result)
  145. return get_raw_buffer(bfr)