Debian Codegraph @

lib/Crypto/Hash/TupleHash128.py

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