MD2.py 6.1 KB

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