PHP替代CryptoJS时Base64编码结果不匹配的技术问询
解决CryptoJS与PHP HMAC-SHA256 Base64编码结果不匹配问题
问题根源
CryptoJS里CryptoJS.HmacSHA256生成的是原始二进制哈希值,后续的Base64编码是直接对这份二进制数据处理。但PHP默认调用hash_hmac('sha256', $phrase, $SecretKey)时,返回的是哈希值的十六进制字符串,你直接对这个字符串做base64_encode,相当于把文本形式的十六进制转成Base64,结果肯定和CryptoJS对二进制编码的结果不一样。
修正后的PHP代码
<?php $SecretKey = 'this is the key'; $phrase = 'this is the phrase'; // 关键:第三个参数传true,获取原始二进制哈希数据 $hashBinary = hash_hmac('sha256', $phrase, $SecretKey, true); $hashInBase64 = base64_encode($hashBinary); // 输出结果:I5qxLInKCXBxBsReeMxeejIBNMgyPSyXGrLPMTC1JW4= echo $hashInBase64; ?>
为什么这样能解决?
当hash_hmac第三个参数设为true时,函数不再返回十六进制字符串,而是直接输出哈希运算后的原始二进制字节流。对这份字节流做Base64编码,逻辑就和CryptoJS里CryptoJS.enc.Base64.stringify(hash)完全对齐,结果自然匹配。
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

