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.
source share