CMAC-AES hashing with PHP

Our API platform uses CMAC-AES hashes as the signature for the request. We have libraries available to create this hash in Java and .NET, but we also need to find a solution for PHP. The problem is that I cannot find anything that seems to reliably generate a hash corresponding to the CMAC generated on our server or through the Java / .NET library.

The only library I found is CryptLib, an alpha library.

https://github.com/ircmaxell/PHP-CryptLib

But it does not generate the same hash, and I'm not good enough to understand why (it forces block sizes to 16 for AES, when what I find on the Internet says that the AES block size is 128).

Any other possibilities I can go down?

+4
source share
1 answer

The PHP-CryptLib library above will eventually work fine. My problem was just my own error related to binary and hexadecimal data.

Using test data provided by the library

require_once 'lib/CryptLib/bootstrap.php'; $hasher = new CryptLib\MAC\Implementation\CMAC; $key = '2b7e151628aed2a6abf7158809cf4f3c'; // from test/Data/Vectors/cmac-aes ... $msg = '6bc1bee22e409f96e93d7e117393172a'; // from test/Data/Vectors/cmac-aes ... $cmac = $hasher->generate($msg,$key); echo $cmac; // $cmac should be 070a16b46b4d4144f79bdd9dd04a287c // actually getting ¢ nd{þ¯\ ¥á¼ÙWß 

Except the CMAC hasher uses binary data, not ascii characters, so you need to pack it with pack ():

 $key = pack("H*", '2b7e151628aed2a6abf7158809cf4f3c'); $msg = pack("H*", '6bc1bee22e409f96e93d7e117393172a'); 

My specific, real thing was trying to hash an arbitrary string, for example:

 $msg = 'Client|Guid-023-23023-23|Guid-0230-2402-252|string|123456|2012-11-08T20:55:34Z'; 

And for this I needed a function:

 function pack_str($str) { $out_str = ""; $len = strlen($str); for($i=0; $i<$len; $i++) { $out_str .= pack("c", ord(substr($str, $i, 1))); } return $out_str; } 

As soon as the data was packed with this function and passed through the hash, I received the CMAC hash that I expected.

+2
source

Source: https://habr.com/ru/post/1444964/


All Articles