| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
from binascii import unhexlify |
| 24 |
|
| 25 |
from Crypto.Hash import BLAKE2s |
| 26 |
from Crypto.Util.strxor import strxor |
| 27 |
from Crypto.Util.number import long_to_bytes, bytes_to_long |
| 28 |
from Crypto.Util.py3compat import bord, tobytes, _copy_bytes |
| 29 |
from Crypto.Random import get_random_bytes |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
digest_size = None |
| 34 |
|
| 35 |
|
| 36 |
def _shift_bytes(bs, xor_lsb=0): |
| 37 |
num = (bytes_to_long(bs) << 1) ^ xor_lsb |
| 38 |
return long_to_bytes(num, len(bs))[-len(bs):] |
| 39 |
|
| 40 |
|
| 41 |
class CMAC(object): |
| 42 |
"""A CMAC hash object. |
| 43 |
Do not instantiate directly. Use the :func:`new` function. |
| 44 |
|
| 45 |
:ivar digest_size: the size in bytes of the resulting MAC tag |
| 46 |
:vartype digest_size: integer |
| 47 |
""" |
| 48 |
|
| 49 |
digest_size = None |
| 50 |
|
| 51 |
def __init__(self, key, msg, ciphermod, cipher_params, mac_len, |
| 52 |
update_after_digest): |
| 53 |
|
| 54 |
self.digest_size = mac_len |
| 55 |
|
| 56 |
self._key = _copy_bytes(None, None, key) |
| 57 |
self._factory = ciphermod |
| 58 |
self._cipher_params = cipher_params |
| 59 |
self._block_size = bs = ciphermod.block_size |
| 60 |
self._mac_tag = None |
| 61 |
self._update_after_digest = update_after_digest |
| 62 |
|
| 63 |
|
| 64 |
if bs == 8: |
| 65 |
const_Rb = 0x1B |
| 66 |
self._max_size = 8 * (2 ** 21) |
| 67 |
elif bs == 16: |
| 68 |
const_Rb = 0x87 |
| 69 |
self._max_size = 16 * (2 ** 48) |
| 70 |
else: |
| 71 |
raise TypeError("CMAC requires a cipher with a block size" |
| 72 |
" of 8 or 16 bytes, not %d" % bs) |
| 73 |
|
| 74 |
|
| 75 |
zero_block = b'\x00' * bs |
| 76 |
self._ecb = ciphermod.new(key, |
| 77 |
ciphermod.MODE_ECB, |
| 78 |
**self._cipher_params) |
| 79 |
L = self._ecb.encrypt(zero_block) |
| 80 |
if bord(L[0]) & 0x80: |
| 81 |
self._k1 = _shift_bytes(L, const_Rb) |
| 82 |
else: |
| 83 |
self._k1 = _shift_bytes(L) |
| 84 |
if bord(self._k1[0]) & 0x80: |
| 85 |
self._k2 = _shift_bytes(self._k1, const_Rb) |
| 86 |
else: |
| 87 |
self._k2 = _shift_bytes(self._k1) |
| 88 |
|
| 89 |
|
| 90 |
self._cbc = ciphermod.new(key, |
| 91 |
ciphermod.MODE_CBC, |
| 92 |
zero_block, |
| 93 |
**self._cipher_params) |
| 94 |
|
| 95 |
|
| 96 |
self._cache = bytearray(bs) |
| 97 |
self._cache_n = 0 |
| 98 |
|
| 99 |
|
| 100 |
self._last_ct = zero_block |
| 101 |
|
| 102 |
|
| 103 |
self._last_pt = None |
| 104 |
|
| 105 |
|
| 106 |
self._data_size = 0 |
| 107 |
|
| 108 |
if msg: |
| 109 |
self.update(msg) |
| 110 |
|
| 111 |
def update(self, msg): |
| 112 |
"""Authenticate the next chunk of message. |
| 113 |
|
| 114 |
Args: |
| 115 |
data (byte string/byte array/memoryview): The next chunk of data |
| 116 |
""" |
| 117 |
|
| 118 |
if self._mac_tag is not None and not self._update_after_digest: |
| 119 |
raise TypeError("update() cannot be called after digest() or verify()") |
| 120 |
|
| 121 |
self._data_size += len(msg) |
| 122 |
bs = self._block_size |
| 123 |
|
| 124 |
if self._cache_n > 0: |
| 125 |
filler = min(bs - self._cache_n, len(msg)) |
| 126 |
self._cache[self._cache_n:self._cache_n+filler] = msg[:filler] |
| 127 |
self._cache_n += filler |
| 128 |
|
| 129 |
if self._cache_n < bs: |
| 130 |
return self |
| 131 |
|
| 132 |
msg = memoryview(msg)[filler:] |
| 133 |
self._update(self._cache) |
| 134 |
self._cache_n = 0 |
| 135 |
|
| 136 |
remain = len(msg) % bs |
| 137 |
if remain > 0: |
| 138 |
self._update(msg[:-remain]) |
| 139 |
self._cache[:remain] = msg[-remain:] |
| 140 |
else: |
| 141 |
self._update(msg) |
| 142 |
self._cache_n = remain |
| 143 |
return self |
| 144 |
|
| 145 |
def _update(self, data_block): |
| 146 |
"""Update a block aligned to the block boundary""" |
| 147 |
|
| 148 |
bs = self._block_size |
| 149 |
assert len(data_block) % bs == 0 |
| 150 |
|
| 151 |
if len(data_block) == 0: |
| 152 |
return |
| 153 |
|
| 154 |
ct = self._cbc.encrypt(data_block) |
| 155 |
if len(data_block) == bs: |
| 156 |
second_last = self._last_ct |
| 157 |
else: |
| 158 |
second_last = ct[-bs*2:-bs] |
| 159 |
self._last_ct = ct[-bs:] |
| 160 |
self._last_pt = strxor(second_last, data_block[-bs:]) |
| 161 |
|
| 162 |
def copy(self): |
| 163 |
"""Return a copy ("clone") of the CMAC object. |
| 164 |
|
| 165 |
The copy will have the same internal state as the original CMAC |
| 166 |
object. |
| 167 |
This can be used to efficiently compute the MAC tag of byte |
| 168 |
strings that share a common initial substring. |
| 169 |
|
| 170 |
:return: An :class:`CMAC` |
| 171 |
""" |
| 172 |
|
| 173 |
obj = self.__new__(CMAC) |
| 174 |
obj.__dict__ = self.__dict__.copy() |
| 175 |
obj._cbc = self._factory.new(self._key, |
| 176 |
self._factory.MODE_CBC, |
| 177 |
self._last_ct, |
| 178 |
**self._cipher_params) |
| 179 |
obj._cache = self._cache[:] |
| 180 |
obj._last_ct = self._last_ct[:] |
| 181 |
return obj |
| 182 |
|
| 183 |
def digest(self): |
| 184 |
"""Return the **binary** (non-printable) MAC tag of the message |
| 185 |
that has been authenticated so far. |
| 186 |
|
| 187 |
:return: The MAC tag, computed over the data processed so far. |
| 188 |
Binary form. |
| 189 |
:rtype: byte string |
| 190 |
""" |
| 191 |
|
| 192 |
bs = self._block_size |
| 193 |
|
| 194 |
if self._mac_tag is not None and not self._update_after_digest: |
| 195 |
return self._mac_tag |
| 196 |
|
| 197 |
if self._data_size > self._max_size: |
| 198 |
raise ValueError("MAC is unsafe for this message") |
| 199 |
|
| 200 |
if self._cache_n == 0 and self._data_size > 0: |
| 201 |
|
| 202 |
pt = strxor(self._last_pt, self._k1) |
| 203 |
else: |
| 204 |
|
| 205 |
partial = self._cache[:] |
| 206 |
partial[self._cache_n:] = b'\x80' + b'\x00' * (bs - self._cache_n - 1) |
| 207 |
pt = strxor(strxor(self._last_ct, partial), self._k2) |
| 208 |
|
| 209 |
self._mac_tag = self._ecb.encrypt(pt)[:self.digest_size] |
| 210 |
|
| 211 |
return self._mac_tag |
| 212 |
|
| 213 |
def hexdigest(self): |
| 214 |
"""Return the **printable** MAC tag of the message authenticated so far. |
| 215 |
|
| 216 |
:return: The MAC tag, computed over the data processed so far. |
| 217 |
Hexadecimal encoded. |
| 218 |
:rtype: string |
| 219 |
""" |
| 220 |
|
| 221 |
return "".join(["%02x" % bord(x) |
| 222 |
for x in tuple(self.digest())]) |
| 223 |
|
| 224 |
def verify(self, mac_tag): |
| 225 |
"""Verify that a given **binary** MAC (computed by another party) |
| 226 |
is valid. |
| 227 |
|
| 228 |
Args: |
| 229 |
mac_tag (byte string/byte array/memoryview): the expected MAC of the message. |
| 230 |
|
| 231 |
Raises: |
| 232 |
ValueError: if the MAC does not match. It means that the message |
| 233 |
has been tampered with or that the MAC key is incorrect. |
| 234 |
""" |
| 235 |
|
| 236 |
secret = get_random_bytes(16) |
| 237 |
|
| 238 |
mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag) |
| 239 |
mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest()) |
| 240 |
|
| 241 |
if mac1.digest() != mac2.digest(): |
| 242 |
raise ValueError("MAC check failed") |
| 243 |
|
| 244 |
def hexverify(self, hex_mac_tag): |
| 245 |
"""Verify that a given **printable** MAC (computed by another party) |
| 246 |
is valid. |
| 247 |
|
| 248 |
Args: |
| 249 |
hex_mac_tag (string): the expected MAC of the message, as a hexadecimal string. |
| 250 |
|
| 251 |
Raises: |
| 252 |
ValueError: if the MAC does not match. It means that the message |
| 253 |
has been tampered with or that the MAC key is incorrect. |
| 254 |
""" |
| 255 |
|
| 256 |
self.verify(unhexlify(tobytes(hex_mac_tag))) |
| 257 |
|
| 258 |
|
| 259 |
def new(key, msg=None, ciphermod=None, cipher_params=None, mac_len=None, |
| 260 |
update_after_digest=False): |
| 261 |
"""Create a new MAC object. |
| 262 |
|
| 263 |
Args: |
| 264 |
key (byte string/byte array/memoryview): |
| 265 |
key for the CMAC object. |
| 266 |
The key must be valid for the underlying cipher algorithm. |
| 267 |
For instance, it must be 16 bytes long for AES-128. |
| 268 |
ciphermod (module): |
| 269 |
A cipher module from :mod:`Crypto.Cipher`. |
| 270 |
The cipher's block size has to be 128 bits, |
| 271 |
like :mod:`Crypto.Cipher.AES`, to reduce the probability |
| 272 |
of collisions. |
| 273 |
msg (byte string/byte array/memoryview): |
| 274 |
Optional. The very first chunk of the message to authenticate. |
| 275 |
It is equivalent to an early call to `CMAC.update`. Optional. |
| 276 |
cipher_params (dict): |
| 277 |
Optional. A set of parameters to use when instantiating a cipher |
| 278 |
object. |
| 279 |
mac_len (integer): |
| 280 |
Length of the MAC, in bytes. |
| 281 |
It must be at least 4 bytes long. |
| 282 |
The default (and recommended) length matches the size of a cipher block. |
| 283 |
update_after_digest (boolean): |
| 284 |
Optional. By default, a hash object cannot be updated anymore after |
| 285 |
the digest is computed. When this flag is ``True``, such check |
| 286 |
is no longer enforced. |
| 287 |
Returns: |
| 288 |
A :class:`CMAC` object |
| 289 |
""" |
| 290 |
|
| 291 |
if ciphermod is None: |
| 292 |
raise TypeError("ciphermod must be specified (try AES)") |
| 293 |
|
| 294 |
cipher_params = {} if cipher_params is None else dict(cipher_params) |
| 295 |
|
| 296 |
if mac_len is None: |
| 297 |
mac_len = ciphermod.block_size |
| 298 |
|
| 299 |
if mac_len < 4: |
| 300 |
raise ValueError("MAC tag length must be at least 4 bytes long") |
| 301 |
|
| 302 |
if mac_len > ciphermod.block_size: |
| 303 |
raise ValueError("MAC tag length cannot be larger than a cipher block (%d) bytes" % ciphermod.block_size) |
| 304 |
|
| 305 |
return CMAC(key, msg, ciphermod, cipher_params, mac_len, |
| 306 |
update_after_digest) |