PHP decrypt CMAC value from AES-128-CBC encrypted NFC tag

93 Views Asked by At

I'm trying to decrypt a NTAG 424 DNA NFC tag using php.

Using the following documentation as a reference: https://www.nxp.com/docs/en/application-note/AN12196.pdf

My IV and key are the following:

$IV = str_repeat("\x00", 16);
$key = str_repeat("\xBE\xEF", 8);

The url I get when the tag is scanned is: /B4D9B7869E3258C8508FB96D6663AA3D/79598DFC270671BD where the first part is the encrypted message and the second part is the CMAC value.

Using the https://packagist.org/packages/cryptlib/cmac package because of this post to try and check if the CMAC value is correct.

Here I created a function where I try and get the CMAC value to check if it's the same as the one in the url.

$crypt = new \CryptLib\MAC\Implementation\CMAC();

$cmacKey = pack("H*", bin2hex($key));
$cmacMsg = pack("H*", $msg);

$cmac = $crypt->generate($cmacMsg, $cmacKey, 8);
$cmac = bin2hex($cmac);

But when I try this, $cmac has the value 78ff8705b76734f3 instead of the expected 79598DFC270671BD.

What am I doing wrong here and how can I get the right CMAC value as the one in the url? (assuming that one is correct)

To decrypt the message and get the picc data tag, uid and counter I use the following:

$ciphertext = openssl_decrypt(hex2bin($msg), 'aes-128-cbc', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $IV);


if ($ciphertext === false) {
    echo "OpenSSL error: " . openssl_error_string();
} else {
    $PICCDataTag = bin2hex(substr($ciphertext, 0, 1));
    $UID = bin2hex(substr($ciphertext, 1, 7));
    $SDMReadCtr = bin2hex(substr($ciphertext, 8, 3));
        
    $counter = 0;

    for ($i = 0; $i < strlen($SDMReadCtr); $i += 2) {
    $counter += hexdec(substr($SDMReadCtr, $i, 2));
    }

Cipher text in hex is: c7048b25aac41390010000ab8f0d7316

This block of code gives me the correct results. However, the $ciphertext contains a last part which I don't use (ab8f0d7316). What is this exactly? Using the pdf I think it is random padding according to 4.4.3.2 table step 8, is this correct?

0

There are 0 best solutions below