Debian Codegraph @

lib/Crypto/Hash/SHA3_512.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # ===================================================================
4 # The contents of this file are dedicated to the public domain. To
5 # the extent that dedication to the public domain is not available,
6 # everyone is granted a worldwide, perpetual, royalty-free,
7 # non-exclusive license to exercise all rights associated with the
8 # contents of this file for any purpose whatsoever.
9 # No rights are reserved.
10 #
11 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
12 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
13 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
14 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
15 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
16 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
17 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
18 # SOFTWARE.
19 # ===================================================================
20
21 from Crypto.Util.py3compat import bord
22
23 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
24 VoidPointer, SmartPointer,
25 create_string_buffer,
26 get_raw_buffer, c_size_t,
27 c_uint8_ptr, c_ubyte)
28
29 from Crypto.Hash.keccak import _raw_keccak_lib
30
31 class SHA3_512_Hash(object):
32 """A SHA3-512 hash object.
33 Do not instantiate directly.
34 Use the :func:`new` function.
35
36 :ivar oid: ASN.1 Object ID
37 :vartype oid: string
38
39 :ivar digest_size: the size in bytes of the resulting hash
40 :vartype digest_size: integer
41 """
42
43 # The size of the resulting hash in bytes.
44 digest_size = 64
45
46 # ASN.1 Object ID
47 oid = "2.16.840.1.101.3.4.2.10"
48
49 # Input block size for HMAC
50 block_size = 72
51
52 def __init__(self, data, update_after_digest):
53 self._update_after_digest = update_after_digest
54 self._digest_done = False
55 self._padding = 0x06
56
57 state = VoidPointer()
58 result = _raw_keccak_lib.keccak_init(state.address_of(),
59 c_size_t(self.digest_size * 2),
60 c_ubyte(24))
61 if result:
62 raise ValueError("Error %d while instantiating SHA-3/512"
63 % result)
64 self._state = SmartPointer(state.get(),
65 _raw_keccak_lib.keccak_destroy)
66 if data:
67 self.update(data)
68
69 def update(self, data):
70 """Continue hashing of a message by consuming the next chunk of data.
71
72 Args:
73 data (byte string/byte array/memoryview): The next chunk of the message being hashed.
74 """
75
76 if self._digest_done and not self._update_after_digest:
77 raise TypeError("You can only call 'digest' or 'hexdigest' on this object")
78
79 result = _raw_keccak_lib.keccak_absorb(self._state.get(),
80 c_uint8_ptr(data),
81 c_size_t(len(data)))
82 if result:
83 raise ValueError("Error %d while updating SHA-3/512"
84 % result)
85 return self
86
87 def digest(self):
88
89 """Return the **binary** (non-printable) digest of the message that has been hashed so far.
90
91 :return: The hash digest, computed over the data processed so far.
92 Binary form.
93 :rtype: byte string
94 """
95
96 self._digest_done = True
97
98 bfr = create_string_buffer(self.digest_size)
99 result = _raw_keccak_lib.keccak_digest(self._state.get(),
100 bfr,
101 c_size_t(self.digest_size),
102 c_ubyte(self._padding))
103 if result:
104 raise ValueError("Error %d while instantiating SHA-3/512"
105 % result)
106
107 self._digest_value = get_raw_buffer(bfr)
108 return self._digest_value
109
110 def hexdigest(self):
111 """Return the **printable** digest of the message that has been hashed so far.
112
113 :return: The hash digest, computed over the data processed so far.
114 Hexadecimal encoded.
115 :rtype: string
116 """
117
118 return "".join(["%02x" % bord(x) for x in self.digest()])
119
120 def copy(self):
121 """Return a copy ("clone") of the hash object.
122
123 The copy will have the same internal state as the original hash
124 object.
125 This can be used to efficiently compute the digests of strings that
126 share a common initial substring.
127
128 :return: A hash object of the same type
129 """
130
131 clone = self.new()
132 result = _raw_keccak_lib.keccak_copy(self._state.get(),
133 clone._state.get())
134 if result:
135 raise ValueError("Error %d while copying SHA3-512" % result)
136 return clone
137
138 def new(self, data=None):
139 """Create a fresh SHA3-521 hash object."""
140
141 return type(self)(data, self._update_after_digest)
142
143
144 def new(*args, **kwargs):
145 """Create a new hash object.
146
147 Args:
148 data (byte string/byte array/memoryview):
149 The very first chunk of the message to hash.
150 It is equivalent to an early call to :meth:`update`.
151 update_after_digest (boolean):
152 Whether :meth:`digest` can be followed by another :meth:`update`
153 (default: ``False``).
154
155 :Return: A :class:`SHA3_512_Hash` hash object
156 """
157
158 data = kwargs.pop("data", None)
159 update_after_digest = kwargs.pop("update_after_digest", False)
160 if len(args) == 1:
161 if data:
162 raise ValueError("Initial data for hash specified twice")
163 data = args[0]
164
165 if kwargs:
166 raise TypeError("Unknown parameters: " + str(kwargs))
167
168 return SHA3_512_Hash(data, update_after_digest)
169
170 # The size of the resulting hash in bytes.
171 digest_size = SHA3_512_Hash.digest_size
172
173 # Input block size for HMAC
174 block_size = 72