Debian Codegraph @

lib/Crypto/Hash/keccak.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2015, 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
32
33 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
34 VoidPointer, SmartPointer,
35 create_string_buffer,
36 get_raw_buffer, c_size_t,
37 c_uint8_ptr, c_ubyte)
38
39 _raw_keccak_lib = load_pycryptodome_raw_lib("Crypto.Hash._keccak",
40 """
41 int keccak_init(void **state,
42 size_t capacity_bytes,
43 uint8_t rounds);
44 int keccak_destroy(void *state);
45 int keccak_absorb(void *state,
46 const uint8_t *in,
47 size_t len);
48 int keccak_squeeze(const void *state,
49 uint8_t *out,
50 size_t len,
51 uint8_t padding);
52 int keccak_digest(void *state,
53 uint8_t *digest,
54 size_t len,
55 uint8_t padding);
56 int keccak_copy(const void *src, void *dst);
57 int keccak_reset(void *state);
58 """)
59
60 class Keccak_Hash(object):
61 """A Keccak hash object.
62 Do not instantiate directly.
63 Use the :func:`new` function.
64
65 :ivar digest_size: the size in bytes of the resulting hash
66 :vartype digest_size: integer
67 """
68
69 def __init__(self, data, digest_bytes, update_after_digest):
70 # The size of the resulting hash in bytes.
71 self.digest_size = digest_bytes
72
73 self._update_after_digest = update_after_digest
74 self._digest_done = False
75 self._padding = 0x01
76
77 state = VoidPointer()
78 result = _raw_keccak_lib.keccak_init(state.address_of(),
79 c_size_t(self.digest_size * 2),
80 c_ubyte(24))
81 if result:
82 raise ValueError("Error %d while instantiating keccak" % result)
83 self._state = SmartPointer(state.get(),
84 _raw_keccak_lib.keccak_destroy)
85 if data:
86 self.update(data)
87
88 def update(self, data):
89 """Continue hashing of a message by consuming the next chunk of data.
90
91 Args:
92 data (byte string/byte array/memoryview): The next chunk of the message being hashed.
93 """
94
95 if self._digest_done and not self._update_after_digest:
96 raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
97
98 result = _raw_keccak_lib.keccak_absorb(self._state.get(),
99 c_uint8_ptr(data),
100 c_size_t(len(data)))
101 if result:
102 raise ValueError("Error %d while updating keccak" % result)
103 return self
104
105 def digest(self):
106 """Return the **binary** (non-printable) digest of the message that has been hashed so far.
107
108 :return: The hash digest, computed over the data processed so far.
109 Binary form.
110 :rtype: byte string
111 """
112
113 self._digest_done = True
114 bfr = create_string_buffer(self.digest_size)
115 result = _raw_keccak_lib.keccak_digest(self._state.get(),
116 bfr,
117 c_size_t(self.digest_size),
118 c_ubyte(self._padding))
119 if result:
120 raise ValueError("Error %d while squeezing keccak" % result)
121
122 return get_raw_buffer(bfr)
123
124 def hexdigest(self):
125 """Return the **printable** digest of the message that has been hashed so far.
126
127 :return: The hash digest, computed over the data processed so far.
128 Hexadecimal encoded.
129 :rtype: string
130 """
131
132 return "".join(["%02x" % bord(x) for x in self.digest()])
133
134 def new(self, **kwargs):
135 """Create a fresh Keccak hash object."""
136
137 if "digest_bytes" not in kwargs and "digest_bits" not in kwargs:
138 kwargs["digest_bytes"] = self.digest_size
139
140 return new(**kwargs)
141
142
143 def new(**kwargs):
144 """Create a new hash object.
145
146 Args:
147 data (bytes/bytearray/memoryview):
148 The very first chunk of the message to hash.
149 It is equivalent to an early call to :meth:`Keccak_Hash.update`.
150 digest_bytes (integer):
151 The size of the digest, in bytes (28, 32, 48, 64).
152 digest_bits (integer):
153 The size of the digest, in bits (224, 256, 384, 512).
154 update_after_digest (boolean):
155 Whether :meth:`Keccak.digest` can be followed by another
156 :meth:`Keccak.update` (default: ``False``).
157
158 :Return: A :class:`Keccak_Hash` hash object
159 """
160
161 data = kwargs.pop("data", None)
162 update_after_digest = kwargs.pop("update_after_digest", False)
163
164 digest_bytes = kwargs.pop("digest_bytes", None)
165 digest_bits = kwargs.pop("digest_bits", None)
166 if None not in (digest_bytes, digest_bits):
167 raise TypeError("Only one digest parameter must be provided")
168 if (None, None) == (digest_bytes, digest_bits):
169 raise TypeError("Digest size (bits, bytes) not provided")
170 if digest_bytes is not None:
171 if digest_bytes not in (28, 32, 48, 64):
172 raise ValueError("'digest_bytes' must be: 28, 32, 48 or 64")
173 else:
174 if digest_bits not in (224, 256, 384, 512):
175 raise ValueError("'digest_bytes' must be: 224, 256, 384 or 512")
176 digest_bytes = digest_bits // 8
177
178 if kwargs:
179 raise TypeError("Unknown parameters: " + str(kwargs))
180
181 return Keccak_Hash(data, digest_bytes, update_after_digest)