|
| 1 | +"""Tests for NTAG cryptographic helpers.""" |
| 2 | + |
| 3 | +from Crypto.Cipher import AES |
| 4 | +from Crypto.Hash import CMAC |
| 5 | + |
| 6 | +from schnee.adapters.ntag.crypt import SDM_SV2_PREFIX, calculate_sdm_mac |
| 7 | + |
| 8 | +TRUNCATED_SDM_MAC_LENGTH = 8 |
| 9 | + |
| 10 | + |
| 11 | +def test_calculate_sdm_mac_with_uid_and_counter() -> None: |
| 12 | + """SDM MAC includes the UID and counter in SV2 when both are present.""" |
| 13 | + assert ( |
| 14 | + calculate_sdm_mac( |
| 15 | + sdm_key=bytes.fromhex("00112233445566778899AABBCCDDEEFF"), |
| 16 | + signed_data=bytes.fromhex("DEADBEEF00"), |
| 17 | + uid=bytes.fromhex("04782E21801D80"), |
| 18 | + counter=bytes.fromhex("010203"), |
| 19 | + ).hex() |
| 20 | + == "7db100f509613111" |
| 21 | + ) |
| 22 | + |
| 23 | + |
| 24 | +def test_calculate_sdm_mac_with_uid_only() -> None: |
| 25 | + """SDM MAC includes only the UID when no counter is provided.""" |
| 26 | + assert ( |
| 27 | + calculate_sdm_mac( |
| 28 | + sdm_key=bytes.fromhex("00112233445566778899AABBCCDDEEFF"), |
| 29 | + signed_data=bytes.fromhex("DEADBEEF00"), |
| 30 | + uid=bytes.fromhex("04782E21801D80"), |
| 31 | + ).hex() |
| 32 | + == "a8e8cc437f54250a" |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +def test_calculate_sdm_mac_without_uid_or_counter() -> None: |
| 37 | + """SDM MAC can be derived from the fixed SV2 prefix alone.""" |
| 38 | + assert ( |
| 39 | + calculate_sdm_mac( |
| 40 | + sdm_key=bytes.fromhex("00112233445566778899AABBCCDDEEFF"), |
| 41 | + signed_data=bytes.fromhex("DEADBEEF00"), |
| 42 | + ).hex() |
| 43 | + == "8330e2018ec638ce" |
| 44 | + ) |
| 45 | + |
| 46 | + |
| 47 | +def test_calculate_sdm_mac_truncates_to_odd_indexed_bytes() -> None: |
| 48 | + """SDM MAC returns the 8-byte [1::2] truncation of the full CMAC.""" |
| 49 | + sdm_key = bytes.fromhex("00112233445566778899AABBCCDDEEFF") |
| 50 | + signed_data = bytes.fromhex("DEADBEEF00") |
| 51 | + uid = bytes.fromhex("04782E21801D80") |
| 52 | + counter = bytes.fromhex("010203") |
| 53 | + |
| 54 | + session_key_cmac = CMAC.new(key=sdm_key, ciphermod=AES) |
| 55 | + session_key_cmac.update(SDM_SV2_PREFIX + uid + counter) |
| 56 | + session_mac_key = session_key_cmac.digest() |
| 57 | + |
| 58 | + full_mac_cmac = CMAC.new(key=session_mac_key, ciphermod=AES) |
| 59 | + full_mac_cmac.update(signed_data) |
| 60 | + full_mac = full_mac_cmac.digest() |
| 61 | + |
| 62 | + assert ( |
| 63 | + calculate_sdm_mac( |
| 64 | + sdm_key=sdm_key, |
| 65 | + signed_data=signed_data, |
| 66 | + uid=uid, |
| 67 | + counter=counter, |
| 68 | + ) |
| 69 | + == full_mac[1::2] |
| 70 | + ) |
| 71 | + assert len(full_mac[1::2]) == TRUNCATED_SDM_MAC_LENGTH |
0 commit comments