MD4.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. """
  31. MD4 is specified in RFC1320_ and produces the 128 bit digest of a message.
  32. >>> from tls.Crypto.Hash import MD4
  33. >>>
  34. >>> h = MD4.new()
  35. >>> h.update(b'Hello')
  36. >>> print h.hexdigest()
  37. MD4 stand for Message Digest version 4, and it was invented by Rivest in 1990.
  38. This algorithm is insecure. Do not use it for new designs.
  39. .. _RFC1320: http://tools.ietf.org/html/rfc1320
  40. """
  41. from tls.Crypto.Util.py3compat import bord
  42. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  43. VoidPointer, SmartPointer,
  44. create_string_buffer,
  45. get_raw_buffer, c_size_t,
  46. c_uint8_ptr)
  47. _raw_md4_lib = load_pycryptodome_raw_lib(
  48. "Crypto.Hash._MD4",
  49. """
  50. int md4_init(void **shaState);
  51. int md4_destroy(void *shaState);
  52. int md4_update(void *hs,
  53. const uint8_t *buf,
  54. size_t len);
  55. int md4_digest(const void *shaState,
  56. uint8_t digest[20]);
  57. int md4_copy(const void *src, void *dst);
  58. """)
  59. class MD4Hash(object):
  60. """Class that implements an MD4 hash
  61. """
  62. #: The size of the resulting hash in bytes.
  63. digest_size = 16
  64. #: The internal block size of the hash algorithm in bytes.
  65. block_size = 64
  66. #: ASN.1 Object ID
  67. oid = "1.2.840.113549.2.4"
  68. def __init__(self, data=None):
  69. state = VoidPointer()
  70. result = _raw_md4_lib.md4_init(state.address_of())
  71. if result:
  72. raise ValueError("Error %d while instantiating MD4"
  73. % result)
  74. self._state = SmartPointer(state.get(),
  75. _raw_md4_lib.md4_destroy)
  76. if data:
  77. self.update(data)
  78. def update(self, data):
  79. """Continue hashing of a message by consuming the next chunk of data.
  80. Repeated calls are equivalent to a single call with the concatenation
  81. of all the arguments. In other words:
  82. >>> m.update(a); m.update(b)
  83. is equivalent to:
  84. >>> m.update(a+b)
  85. :Parameters:
  86. data : byte string/byte array/memoryview
  87. The next chunk of the message being hashed.
  88. """
  89. result = _raw_md4_lib.md4_update(self._state.get(),
  90. c_uint8_ptr(data),
  91. c_size_t(len(data)))
  92. if result:
  93. raise ValueError("Error %d while instantiating MD4"
  94. % result)
  95. def digest(self):
  96. """Return the **binary** (non-printable) digest of the message that
  97. has been hashed so far.
  98. This method does not change the state of the hash object.
  99. You can continue updating the object after calling this function.
  100. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII
  101. characters, including null bytes.
  102. """
  103. bfr = create_string_buffer(self.digest_size)
  104. result = _raw_md4_lib.md4_digest(self._state.get(),
  105. bfr)
  106. if result:
  107. raise ValueError("Error %d while instantiating MD4"
  108. % result)
  109. return get_raw_buffer(bfr)
  110. def hexdigest(self):
  111. """Return the **printable** digest of the message that has been
  112. hashed so far.
  113. This method does not change the state of the hash object.
  114. :Return: A string of 2* `digest_size` characters. It contains only
  115. hexadecimal ASCII digits.
  116. """
  117. return "".join(["%02x" % bord(x) for x in self.digest()])
  118. def copy(self):
  119. """Return a copy ("clone") of the hash object.
  120. The copy will have the same internal state as the original hash
  121. object.
  122. This can be used to efficiently compute the digests of strings that
  123. share a common initial substring.
  124. :Return: A hash object of the same type
  125. """
  126. clone = MD4Hash()
  127. result = _raw_md4_lib.md4_copy(self._state.get(),
  128. clone._state.get())
  129. if result:
  130. raise ValueError("Error %d while copying MD4" % result)
  131. return clone
  132. def new(self, data=None):
  133. return MD4Hash(data)
  134. def new(data=None):
  135. """Return a fresh instance of the hash object.
  136. :Parameters:
  137. data : byte string/byte array/memoryview
  138. The very first chunk of the message to hash.
  139. It is equivalent to an early call to `MD4Hash.update()`.
  140. Optional.
  141. :Return: A `MD4Hash` object
  142. """
  143. return MD4Hash().new(data)
  144. #: The size of the resulting hash in bytes.
  145. digest_size = MD4Hash.digest_size
  146. #: The internal block size of the hash algorithm in bytes.
  147. block_size = MD4Hash.block_size