Debian Codegraph @

lib/Crypto/Hash/HMAC.py

raw symbols SCIP
1 #
2 # HMAC.py - Implements the HMAC algorithm as described by RFC 2104.
3 #
4 # ===================================================================
5 #
6 # Copyright (c) 2014, Legrandin <[email protected]>
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in
17 # the documentation and/or other materials provided with the
18 # distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 # POSSIBILITY OF SUCH DAMAGE.
32 # ===================================================================
33
34 from Crypto.Util.py3compat import bord, tobytes
35
36 from binascii import unhexlify
37
38 from Crypto.Hash import BLAKE2s
39 from Crypto.Util.strxor import strxor
40 from Crypto.Random import get_random_bytes
41
42 __all__ = ['new', 'HMAC']
43
44 _hash2hmac_oid = {
45 '1.3.14.3.2.26': '1.2.840.113549.2.7', # SHA-1
46 '2.16.840.1.101.3.4.2.4': '1.2.840.113549.2.8', # SHA-224
47 '2.16.840.1.101.3.4.2.1': '1.2.840.113549.2.9', # SHA-256
48 '2.16.840.1.101.3.4.2.2': '1.2.840.113549.2.10', # SHA-384
49 '2.16.840.1.101.3.4.2.3': '1.2.840.113549.2.11', # SHA-512
50 '2.16.840.1.101.3.4.2.5': '1.2.840.113549.2.12', # SHA-512_224
51 '2.16.840.1.101.3.4.2.6': '1.2.840.113549.2.13', # SHA-512_256
52 '2.16.840.1.101.3.4.2.7': '2.16.840.1.101.3.4.2.13', # SHA-3 224
53 '2.16.840.1.101.3.4.2.8': '2.16.840.1.101.3.4.2.14', # SHA-3 256
54 '2.16.840.1.101.3.4.2.9': '2.16.840.1.101.3.4.2.15', # SHA-3 384
55 '2.16.840.1.101.3.4.2.10': '2.16.840.1.101.3.4.2.16', # SHA-3 512
56 }
57
58 _hmac2hash_oid = {v: k for k, v in _hash2hmac_oid.items()}
59
60
61 class HMAC(object):
62 """An HMAC hash object.
63 Do not instantiate directly. Use the :func:`new` function.
64
65 :ivar digest_size: the size in bytes of the resulting MAC tag
66 :vartype digest_size: integer
67
68 :ivar oid: the ASN.1 object ID of the HMAC algorithm.
69 Only present if the algorithm was officially assigned one.
70 """
71
72 def __init__(self, key, msg=b"", digestmod=None):
73
74 if digestmod is None:
75 from Crypto.Hash import MD5
76 digestmod = MD5
77
78 if msg is None:
79 msg = b""
80
81 # Size of the MAC tag
82 self.digest_size = digestmod.digest_size
83
84 self._digestmod = digestmod
85
86 # Hash OID --> HMAC OID
87 try:
88 self.oid = _hash2hmac_oid[digestmod.oid]
89 except (KeyError, AttributeError):
90 pass
91
92 if isinstance(key, memoryview):
93 key = key.tobytes()
94
95 try:
96 if len(key) <= digestmod.block_size:
97 # Step 1 or 2
98 key_0 = key + b"\x00" * (digestmod.block_size - len(key))
99 else:
100 # Step 3
101 hash_k = digestmod.new(key).digest()
102 key_0 = hash_k + b"\x00" * (digestmod.block_size - len(hash_k))
103 except AttributeError:
104 # Not all hash types have "block_size"
105 raise ValueError("Hash type incompatible to HMAC")
106
107 # Step 4
108 key_0_ipad = strxor(key_0, b"\x36" * len(key_0))
109
110 # Start step 5 and 6
111 self._inner = digestmod.new(key_0_ipad)
112 self._inner.update(msg)
113
114 # Step 7
115 key_0_opad = strxor(key_0, b"\x5c" * len(key_0))
116
117 # Start step 8 and 9
118 self._outer = digestmod.new(key_0_opad)
119
120 def update(self, msg):
121 """Authenticate the next chunk of message.
122
123 Args:
124 data (byte string/byte array/memoryview): The next chunk of data
125 """
126
127 self._inner.update(msg)
128 return self
129
130 def _pbkdf2_hmac_assist(self, first_digest, iterations):
131 """Carry out the expensive inner loop for PBKDF2-HMAC"""
132
133 result = self._digestmod._pbkdf2_hmac_assist(
134 self._inner,
135 self._outer,
136 first_digest,
137 iterations)
138 return result
139
140 def copy(self):
141 """Return a copy ("clone") of the HMAC object.
142
143 The copy will have the same internal state as the original HMAC
144 object.
145 This can be used to efficiently compute the MAC tag of byte
146 strings that share a common initial substring.
147
148 :return: An :class:`HMAC`
149 """
150
151 new_hmac = HMAC(b"fake key", digestmod=self._digestmod)
152
153 # Syncronize the state
154 new_hmac._inner = self._inner.copy()
155 new_hmac._outer = self._outer.copy()
156
157 return new_hmac
158
159 def digest(self):
160 """Return the **binary** (non-printable) MAC tag of the message
161 authenticated so far.
162
163 :return: The MAC tag digest, computed over the data processed so far.
164 Binary form.
165 :rtype: byte string
166 """
167
168 frozen_outer_hash = self._outer.copy()
169 frozen_outer_hash.update(self._inner.digest())
170 return frozen_outer_hash.digest()
171
172 def verify(self, mac_tag):
173 """Verify that a given **binary** MAC (computed by another party)
174 is valid.
175
176 Args:
177 mac_tag (byte string/byte string/memoryview): the expected MAC of the message.
178
179 Raises:
180 ValueError: if the MAC does not match. It means that the message
181 has been tampered with or that the MAC key is incorrect.
182 """
183
184 secret = get_random_bytes(16)
185
186 mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
187 mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())
188
189 if mac1.digest() != mac2.digest():
190 raise ValueError("MAC check failed")
191
192 def hexdigest(self):
193 """Return the **printable** MAC tag of the message authenticated so far.
194
195 :return: The MAC tag, computed over the data processed so far.
196 Hexadecimal encoded.
197 :rtype: string
198 """
199
200 return "".join(["%02x" % bord(x)
201 for x in tuple(self.digest())])
202
203 def hexverify(self, hex_mac_tag):
204 """Verify that a given **printable** MAC (computed by another party)
205 is valid.
206
207 Args:
208 hex_mac_tag (string): the expected MAC of the message,
209 as a hexadecimal string.
210
211 Raises:
212 ValueError: if the MAC does not match. It means that the message
213 has been tampered with or that the MAC key is incorrect.
214 """
215
216 self.verify(unhexlify(tobytes(hex_mac_tag)))
217
218
219 def new(key, msg=b"", digestmod=None):
220 """Create a new MAC object.
221
222 Args:
223 key (bytes/bytearray/memoryview):
224 key for the MAC object.
225 It must be long enough to match the expected security level of the
226 MAC.
227 msg (bytes/bytearray/memoryview):
228 Optional. The very first chunk of the message to authenticate.
229 It is equivalent to an early call to :meth:`HMAC.update`.
230 digestmod (module):
231 The hash to use to implement the HMAC.
232 Default is :mod:`Crypto.Hash.MD5`.
233
234 Returns:
235 An :class:`HMAC` object
236 """
237
238 return HMAC(key, msg, digestmod)