Skip to content

Commit 40b1dea

Browse files
committed
aes-cmac: aes-cmac function using cryptolib.
Signed-off-by: Kian_Bahasadri <[email protected]>
1 parent 98f8a7e commit 40b1dea

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

python-ecosys/aes-cmac/aes_cmac.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/python3
2+
3+
import cryptolib
4+
from binascii import hexlify
5+
from math import ceil
6+
7+
8+
class CMAC:
9+
def _xor(self, a, b):
10+
return bytes(x ^ y for x, y in zip(a, b))
11+
12+
def _e(self, key, plain):
13+
aes = cryptolib.aes(key, 1) # Using ECB mode
14+
return aes.encrypt(plain)
15+
16+
def _d(self, key, enc):
17+
aes = cryptolib.aes(key, 1) # Using ECB mode
18+
return aes.decrypt(enc)
19+
20+
def generate_subkey(self, k):
21+
const_zero = b"\x00" * 16
22+
const_rb = b"\x87" + b"\x00" * 15 # Adjusted to align with common CMAC practices
23+
24+
# Step 1
25+
l = self._e(k, const_zero)
26+
27+
# Step 2 and 3
28+
def shift_left(bit_string):
29+
shifted = int.from_bytes(bit_string, "big") << 1
30+
if bit_string[0] & 0x80:
31+
shifted ^= 0x100000000000000000000000000000087 # Apply Rb polynomial
32+
return shifted.to_bytes(16, "big")
33+
34+
k1 = shift_left(l)
35+
k2 = shift_left(k1)
36+
37+
return k1, k2
38+
39+
def aes_cmac(self, k, m):
40+
const_zero = b"\x00" * 16
41+
const_bsize = 16
42+
43+
# Step 1
44+
k1, k2 = self.generate_subkey(k)
45+
46+
# Step 2
47+
n = ceil(len(m) / const_bsize)
48+
m_block = [m[i * const_bsize : (i + 1) * const_bsize] for i in range(n)]
49+
50+
# Step 3
51+
if n == 0:
52+
n = 1
53+
m_block = [b""]
54+
flag = False
55+
else:
56+
flag = len(m) % const_bsize == 0
57+
58+
# Step 4
59+
if flag:
60+
m_last = self._xor(m_block[-1], k1)
61+
else:
62+
padding = b"\x80" + b"\x00" * (const_bsize - len(m_block[-1]) - 1)
63+
m_last = self._xor(m_block[-1] + padding, k2)
64+
65+
# Step 5 and 6
66+
x = const_zero
67+
for block in m_block[:-1]:
68+
y = self._xor(x, block)
69+
x = self._e(k, y)
70+
y = self._xor(m_last, x)
71+
t = self._e(k, y)
72+
73+
# Step 7
74+
return t

python-ecosys/aes-cmac/manifest.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
metadata(description="CMAC using AES from built in cryptolib library", version="0.1.0")
2+
module("aes_cmac.py")

0 commit comments

Comments
 (0)