MD5.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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 *
  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. _raw_md5_lib = load_pycryptodome_raw_lib("Cryptodome.Hash._MD5",
  27. """
  28. #define MD5_DIGEST_SIZE 16
  29. int MD5_init(void **shaState);
  30. int MD5_destroy(void *shaState);
  31. int MD5_update(void *hs,
  32. const uint8_t *buf,
  33. size_t len);
  34. int MD5_digest(const void *shaState,
  35. uint8_t digest[MD5_DIGEST_SIZE]);
  36. int MD5_copy(const void *src, void *dst);
  37. int MD5_pbkdf2_hmac_assist(const void *inner,
  38. const void *outer,
  39. const uint8_t first_digest[MD5_DIGEST_SIZE],
  40. uint8_t final_digest[MD5_DIGEST_SIZE],
  41. size_t iterations);
  42. """)
  43. class MD5Hash(object):
  44. """A MD5 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 = 16
  57. # The internal block size of the hash algorithm in bytes.
  58. block_size = 64
  59. # ASN.1 Object ID
  60. oid = "1.2.840.113549.2.5"
  61. def __init__(self, data=None):
  62. state = VoidPointer()
  63. result = _raw_md5_lib.MD5_init(state.address_of())
  64. if result:
  65. raise ValueError("Error %d while instantiating MD5"
  66. % result)
  67. self._state = SmartPointer(state.get(),
  68. _raw_md5_lib.MD5_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_md5_lib.MD5_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 MD5"
  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_md5_lib.MD5_digest(self._state.get(),
  90. bfr)
  91. if result:
  92. raise ValueError("Error %d while instantiating MD5"
  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 = MD5Hash()
  111. result = _raw_md5_lib.MD5_copy(self._state.get(),
  112. clone._state.get())
  113. if result:
  114. raise ValueError("Error %d while copying MD5" % result)
  115. return clone
  116. def new(self, data=None):
  117. """Create a fresh SHA-1 hash object."""
  118. return MD5Hash(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:`MD5Hash.update`.
  124. :type data: byte string/byte array/memoryview
  125. :Return: A :class:`MD5Hash` hash object
  126. """
  127. return MD5Hash().new(data)
  128. # The size of the resulting hash in bytes.
  129. digest_size = 16
  130. # The internal block size of the hash algorithm in bytes.
  131. block_size = 64
  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_md5_lib.MD5_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 MD5" % result)
  145. return get_raw_buffer(bfr)