RIPEMD160.py 6.4 KB

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