Debian Codegraph @

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