我有一个CMAC计算的例子,我想用Python来再现它,但是我失败了。该示例如下所示:
key = 3ED0920E5E6A0320D823D5987FEAFBB1
msg = CEE9A53E3E463EF1F459635736738962&cmac=预期的(截断的) CMAC如下所示(注意:截断表示每一个字节被删除)
ECC1E7F6C6C73BF6因此,我尝试用下面的代码来重现这个示例:
from Crypto.Hash import CMAC
from Crypto.Cipher import AES
from binascii import hexlify, unhexlify
def generate_cmac(key, msg):
"""generate a truncated cmac message.
Inputs:
key: 1-dimensional bytearray of arbitrary length
msg: 1-dimensional bytearray of arbitrary length
Outputs:
CMAC: The cmac number
CMAC_t: Trunacted CMAC"""
# Generate CMAC via the CMAC algorithm
cobj = CMAC.new(key=key, ciphermod=AES)
cobj.update(msg)
mac_raw = cobj.digest()
# Truncate by initializing an empty array and assigning every second byte
mac_truncated = bytearray(8 * b'\x00')
it2 = 0
for it in range(len(mac_raw)):
if it % 2:
mac_truncated[it2:it2+1] = mac_raw[it:it+1]
it2 += 1
return mac_raw, mac_truncated
key = unhexlify('3ED0920E5E6A0320D823D5987FEAFBB1') # The key as in the example
msg = 'CEE9A53E3E463EF1F459635736738962&cmac=' # The msg as in the example
msg_utf = msg.encode('utf-8')
msg_input = hexlify(msg_utf) # Trying to get the bytearray
mac, mact_calc = generate_cmac(key, msg_input) # Calculate the CMAC and truncated CMAC
# However the calculated CMAC does not match the cmac of the example我的函数generate_cmac()在其他情况下可以很好地工作,为什么不适合这个例子呢?
(如果有人好奇的话,这个例子来自本文件页面18/表6)
编辑:成功的cmac计算示例如下:
mact_expected = unhexlify('94EED9EE65337086') # as stated in the application note
key = unhexlify('3FB5F6E3A807A03D5E3570ACE393776F') # called K_SesSDMFileReadMAC
msg = [] # zero length input
mac, mact_calc = generate_cmac(key, msg) # mact_expected and mact_calc are the same
assert mact_expected == mact_calc, "Example 1 failed" # This assertion passes发布于 2020-04-06 19:48:59
TLDR:overhexlification
让我大吃一惊的是,链接示例实际上似乎意味着CEE9A53E3E463EF1F459635736738962&cmac=,因为下面的框包含76个十六进制字符,用于ASCII中的38个字节编码,即434545394135334533453436334546314634353936333537333637333839363226636d61633d。
不过,我确信这不需要像代码那样以76字节为单位进行进一步的半成品化。换句话说,我的赌注就在
key = unhexlify('3ED0920E5E6A0320D823D5987FEAFBB1')
msg = 'CEE9A53E3E463EF1F459635736738962&cmac='.encode()
mac, mact_calc = generate_cmac(key, msg)https://stackoverflow.com/questions/61333496
复制相似问题