本文介绍了OpenSSL HMAC-SHA1摘要与加密的不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了6个小时来实现消息签名算法.它根本无法正常工作:

I've spent past 6 hours implementing message signing algorithm.. It does not work AT ALL:

这是生成摘要的PHP代码:

This is PHP code to generate digest:

$payload = "thisisanapple";
$signature = hash_hmac("sha1", $payload, "thisisarandomkey");
$data = base64_encode($signature);
// YzExZWRmZDliMjQzNTZjNzhlNmE3ZTdmMDE3ODJjNmMxMmM4ZTllMQ==

这是在Node.js服务器上运行的JS,其作用相同:

This is JS running on the Node.js server doing the same thing:

var hmac = crypto.createHmac('sha1', "thisisarandomkey");
hmac.update("thisisanapple");
var signature = hmac.digest('base64');
// wR7f2bJDVseOan5/AXgsbBLI6eE=

我不知道这里出了什么问题.我尝试了SHA256,但它们仍然有所不同.在明文和base64中,我还使用了由OpenSSL生成的私钥,结果仍然相同(不同的密钥).

I have no clue what is wrong here.. I have tries SHA256, but they still differ. I also used a private key generated with OpenSSL, both in plaintext and in base64, still same result (different keys).

推荐答案

hash_hmac具有四个参数,最后一个指定输出,默认情况下hash_hmac返回十六进制字符串,而不是原始数据.因此base64_encode在PHP代码片段中对十六进制字符串进行编码.

hash_hmac has four parameters and the last one specifies the output and by default hash_hmac returns hex string, not the raw data. So base64_encode encodes hex string in the PHP code fragment.

这将很好地工作:

$payload = "thisisanapple";
$signature = hash_hmac("sha1", $payload, "thisisarandomkey", true);
$data = base64_encode($signature);
// wR7f2bJDVseOan5/AXgsbBLI6eE=

这篇关于OpenSSL HMAC-SHA1摘要与加密的不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 15:04