Debian Codegraph @

lib/Crypto/Hash/SHA512.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)
28
29 _raw_sha512_lib = load_pycryptodome_raw_lib("Crypto.Hash._SHA512",
30 """
31 int SHA512_init(void **shaState,
32 size_t digest_size);
33 int SHA512_destroy(void *shaState);
34 int SHA512_update(void *hs,
35 const uint8_t *buf,
36 size_t len);
37 int SHA512_digest(const void *shaState,
38 uint8_t *digest,
39 size_t digest_size);
40 int SHA512_copy(const void *src, void *dst);
41
42 int SHA512_pbkdf2_hmac_assist(const void *inner,
43 const void *outer,
44 const uint8_t *first_digest,
45 uint8_t *final_digest,
46 size_t iterations,
47 size_t digest_size);
48 """)
49
50 class SHA512Hash(object):
51 """A SHA-512 hash object (possibly in its truncated version SHA-512/224 or
52 SHA-512/256.
53 Do not instantiate directly. Use the :func:`new` function.
54
55 :ivar oid: ASN.1 Object ID
56 :vartype oid: string
57
58 :ivar block_size: the size in bytes of the internal message block,
59 input to the compression function
60 :vartype block_size: integer
61
62 :ivar digest_size: the size in bytes of the resulting hash
63 :vartype digest_size: integer
64 """
65
66 # The internal block size of the hash algorithm in bytes.
67 block_size = 128
68
69 def __init__(self, data, truncate):
70 self._truncate = truncate
71
72 if truncate is None:
73 self.oid = "2.16.840.1.101.3.4.2.3"
74 self.digest_size = 64
75 elif truncate == "224":
76 self.oid = "2.16.840.1.101.3.4.2.5"
77 self.digest_size = 28
78 elif truncate == "256":
79 self.oid = "2.16.840.1.101.3.4.2.6"
80 self.digest_size = 32
81 else:
82 raise ValueError("Incorrect truncation length. It must be '224' or '256'.")
83
84 state = VoidPointer()
85 result = _raw_sha512_lib.SHA512_init(state.address_of(),
86 c_size_t(self.digest_size))
87 if result:
88 raise ValueError("Error %d while instantiating SHA-512"
89 % result)
90 self._state = SmartPointer(state.get(),
91 _raw_sha512_lib.SHA512_destroy)
92 if data:
93 self.update(data)
94
95 def update(self, data):
96 """Continue hashing of a message by consuming the next chunk of data.
97
98 Args:
99 data (byte string/byte array/memoryview): The next chunk of the message being hashed.
100 """
101
102 result = _raw_sha512_lib.SHA512_update(self._state.get(),
103 c_uint8_ptr(data),
104 c_size_t(len(data)))
105 if result:
106 raise ValueError("Error %d while hashing data with SHA512"
107 % result)
108
109 def digest(self):
110 """Return the **binary** (non-printable) digest of the message that has been hashed so far.
111
112 :return: The hash digest, computed over the data processed so far.
113 Binary form.
114 :rtype: byte string
115 """
116
117 bfr = create_string_buffer(self.digest_size)
118 result = _raw_sha512_lib.SHA512_digest(self._state.get(),
119 bfr,
120 c_size_t(self.digest_size))
121 if result:
122 raise ValueError("Error %d while making SHA512 digest"
123 % result)
124
125 return get_raw_buffer(bfr)
126
127 def hexdigest(self):
128 """Return the **printable** digest of the message that has been hashed so far.
129
130 :return: The hash digest, computed over the data processed so far.
131 Hexadecimal encoded.
132 :rtype: string
133 """
134
135 return "".join(["%02x" % bord(x) for x in self.digest()])
136
137 def copy(self):
138 """Return a copy ("clone") of the hash object.
139
140 The copy will have the same internal state as the original hash
141 object.
142 This can be used to efficiently compute the digests of strings that
143 share a common initial substring.
144
145 :return: A hash object of the same type
146 """
147
148 clone = SHA512Hash(None, self._truncate)
149 result = _raw_sha512_lib.SHA512_copy(self._state.get(),
150 clone._state.get())
151 if result:
152 raise ValueError("Error %d while copying SHA512" % result)
153 return clone
154
155 def new(self, data=None):
156 """Create a fresh SHA-512 hash object."""
157
158 return SHA512Hash(data, self._truncate)
159
160
161 def new(data=None, truncate=None):
162 """Create a new hash object.
163
164 Args:
165 data (bytes/bytearray/memoryview):
166 Optional. The very first chunk of the message to hash.
167 It is equivalent to an early call to :meth:`SHA512Hash.update`.
168 truncate (string):
169 Optional. The desired length of the digest. It can be either "224" or
170 "256". If not present, the digest is 512 bits long.
171 Passing this parameter is **not** equivalent to simply truncating
172 the output digest.
173
174 :Return: A :class:`SHA512Hash` hash object
175 """
176
177 return SHA512Hash(data, truncate)
178
179
180 # The size of the full SHA-512 hash in bytes.
181 digest_size = 64
182
183 # The internal block size of the hash algorithm in bytes.
184 block_size = 128
185
186
187 def _pbkdf2_hmac_assist(inner, outer, first_digest, iterations):
188 """Compute the expensive inner loop in PBKDF-HMAC."""
189
190 assert iterations > 0
191
192 bfr = create_string_buffer(len(first_digest));
193 result = _raw_sha512_lib.SHA512_pbkdf2_hmac_assist(
194 inner._state.get(),
195 outer._state.get(),
196 first_digest,
197 bfr,
198 c_size_t(iterations),
199 c_size_t(len(first_digest)))
200
201 if result:
202 raise ValueError("Error %d with PBKDF2-HMAC assist for SHA512" % result)
203
204 return get_raw_buffer(bfr)