| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 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', |
| 46 |
'2.16.840.1.101.3.4.2.4': '1.2.840.113549.2.8', |
| 47 |
'2.16.840.1.101.3.4.2.1': '1.2.840.113549.2.9', |
| 48 |
'2.16.840.1.101.3.4.2.2': '1.2.840.113549.2.10', |
| 49 |
'2.16.840.1.101.3.4.2.3': '1.2.840.113549.2.11', |
| 50 |
'2.16.840.1.101.3.4.2.5': '1.2.840.113549.2.12', |
| 51 |
'2.16.840.1.101.3.4.2.6': '1.2.840.113549.2.13', |
| 52 |
'2.16.840.1.101.3.4.2.7': '2.16.840.1.101.3.4.2.13', |
| 53 |
'2.16.840.1.101.3.4.2.8': '2.16.840.1.101.3.4.2.14', |
| 54 |
'2.16.840.1.101.3.4.2.9': '2.16.840.1.101.3.4.2.15', |
| 55 |
'2.16.840.1.101.3.4.2.10': '2.16.840.1.101.3.4.2.16', |
| 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 |
|
| 82 |
self.digest_size = digestmod.digest_size |
| 83 |
|
| 84 |
self._digestmod = digestmod |
| 85 |
|
| 86 |
|
| 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 |
|
| 98 |
key_0 = key + b"\x00" * (digestmod.block_size - len(key)) |
| 99 |
else: |
| 100 |
|
| 101 |
hash_k = digestmod.new(key).digest() |
| 102 |
key_0 = hash_k + b"\x00" * (digestmod.block_size - len(hash_k)) |
| 103 |
except AttributeError: |
| 104 |
|
| 105 |
raise ValueError("Hash type incompatible to HMAC") |
| 106 |
|
| 107 |
|
| 108 |
key_0_ipad = strxor(key_0, b"\x36" * len(key_0)) |
| 109 |
|
| 110 |
|
| 111 |
self._inner = digestmod.new(key_0_ipad) |
| 112 |
self._inner.update(msg) |
| 113 |
|
| 114 |
|
| 115 |
key_0_opad = strxor(key_0, b"\x5c" * len(key_0)) |
| 116 |
|
| 117 |
|
| 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 |
|
| 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) |