TupleHash128.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2021, 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 Crypto.Util.py3compat import bord, is_bytes, tobytes
  31. from . import cSHAKE128
  32. from .cSHAKE128 import _encode_str, _right_encode
  33. class TupleHash(object):
  34. """A Tuple hash object.
  35. Do not instantiate directly.
  36. Use the :func:`new` function.
  37. """
  38. def __init__(self, custom, cshake, digest_size):
  39. self.digest_size = digest_size
  40. self._cshake = cshake._new(b'', custom, b'TupleHash')
  41. self._digest = None
  42. def update(self, *data):
  43. """Authenticate the next tuple of byte strings.
  44. TupleHash guarantees the logical separation between each byte string.
  45. Args:
  46. data (bytes/bytearray/memoryview): One or more items to hash.
  47. """
  48. if self._digest is not None:
  49. raise TypeError("You cannot call 'update' after 'digest' or 'hexdigest'")
  50. for item in data:
  51. if not is_bytes(item):
  52. raise TypeError("You can only call 'update' on bytes" )
  53. self._cshake.update(_encode_str(item))
  54. return self
  55. def digest(self):
  56. """Return the **binary** (non-printable) digest of the tuple of byte strings.
  57. :return: The hash digest. Binary form.
  58. :rtype: byte string
  59. """
  60. if self._digest is None:
  61. self._cshake.update(_right_encode(self.digest_size * 8))
  62. self._digest = self._cshake.read(self.digest_size)
  63. return self._digest
  64. def hexdigest(self):
  65. """Return the **printable** digest of the tuple of byte strings.
  66. :return: The hash digest. Hexadecimal encoded.
  67. :rtype: string
  68. """
  69. return "".join(["%02x" % bord(x) for x in tuple(self.digest())])
  70. def new(self, **kwargs):
  71. """Return a new instance of a TupleHash object.
  72. See :func:`new`.
  73. """
  74. if "digest_bytes" not in kwargs and "digest_bits" not in kwargs:
  75. kwargs["digest_bytes"] = self.digest_size
  76. return new(**kwargs)
  77. def new(**kwargs):
  78. """Create a new TupleHash128 object.
  79. Args:
  80. digest_bytes (integer):
  81. Optional. The size of the digest, in bytes.
  82. Default is 64. Minimum is 8.
  83. digest_bits (integer):
  84. Optional and alternative to ``digest_bytes``.
  85. The size of the digest, in bits (and in steps of 8).
  86. Default is 512. Minimum is 64.
  87. custom (bytes):
  88. Optional.
  89. A customization bytestring (``S`` in SP 800-185).
  90. :Return: A :class:`TupleHash` object
  91. """
  92. digest_bytes = kwargs.pop("digest_bytes", None)
  93. digest_bits = kwargs.pop("digest_bits", None)
  94. if None not in (digest_bytes, digest_bits):
  95. raise TypeError("Only one digest parameter must be provided")
  96. if (None, None) == (digest_bytes, digest_bits):
  97. digest_bytes = 64
  98. if digest_bytes is not None:
  99. if digest_bytes < 8:
  100. raise ValueError("'digest_bytes' must be at least 8")
  101. else:
  102. if digest_bits < 64 or digest_bits % 8:
  103. raise ValueError("'digest_bytes' must be at least 64 "
  104. "in steps of 8")
  105. digest_bytes = digest_bits // 8
  106. custom = kwargs.pop("custom", b'')
  107. return TupleHash(custom, cSHAKE128, digest_bytes)