我试图复制HMAC签名描述的这里。
这个例子是使用来自nodejs的nodejs,但是在我的例子中,我需要使用Google闭包库。因此,我尝试使用goog.crypt.Hmac库复制HMAC签名。
下面是我的实验代码。
let crypto = require('crypto');
require("google-closure-library");
goog.require("goog.crypt.Hmac");
goog.require("goog.crypt");
goog.require('goog.crypt.Sha1');
function forceUnicodeEncoding(string) {
return decodeURIComponent(encodeURIComponent(string));
}
function nodejs_crypto(string_to_sign, secret) {
signature = crypto.createHmac('sha1', secret)
.update(forceUnicodeEncoding(string_to_sign))
.digest('base64')
.trim();
return signature
}
function goog_crypto(string_to_sign, secret) {
const hmac = new goog.crypt.Hmac(new goog.crypt.Sha1(), goog.crypt.stringToByteArray(secret));
const hash = hmac.getHmac(forceUnicodeEncoding(string_to_sign));
return hash.toString()
}
const string_to_sign = "message";
const secret = "secret";
const sig1 = nodejs_crypto(string_to_sign, secret);
const sig2 = goog_crypto(string_to_sign, secret);
console.log(sig1);
// DK9kn+7klT2Hv5A6wRdsReAo3xY=
console.log(sig2);
// 12,175,100,159,238,228,149,61,135,191,144,58,193,23,108,69,224,40,223,22
我很难在网上找到goog.crypt.Hmac的任何例子。
以下是我的问题:
goog_crypto的实现是否正确。hash.String()返回类似数组的东西?发布于 2019-10-10 06:30:06
getHmac的返回值,即代码中的hash,是整数的数组-作为记录在这里 .array.toString()与array.join()非常相似。i.e
function goog_crypto(string_to_sign, secret) {
const hmac = new goog.crypt.Hmac(new goog.crypt.Sha1(), goog.crypt.stringToByteArray(secret));
const hash = hmac.getHmac(forceUnicodeEncoding(string_to_sign));
return Buffer.from(hash).toString('base64');
}因为hash是Numbers的数组,所以Buffer.from(hash)根据hash中的数字创建一个缓冲区- buffer.toString('base64')返回以base64编码的缓冲区数据。
关于第一点:为了证明您在代码中获得的结果是相同的
const sig1 = "DK9kn+7klT2Hv5A6wRdsReAo3xY=";
const sig2 = '12,175,100,159,238,228,149,61,135,191,144,58,193,23,108,69,224,40,223,22';
const sig1AsNumArrayString = atob(sig1).split('').map(c => c.charCodeAt(0)).toString();
console.log(sig2 === sig1AsNumArrayString)
https://stackoverflow.com/questions/58316424
复制相似问题