Ale*_*exR 5 javascript hash digest-authentication node.js google-apps-script
我想将以下Node.JS代码段转换为JavaScript在Google Apps脚本中运行它:
来自:Node.JS
function getMessageSignature(path, request, nonce) {
var message = querystring.stringify(request);
var secret = new Buffer(config.secret, 'base64');
var hash = new crypto.createHash('sha256');
var hmac = new crypto.createHmac('sha512', secret);
var hash_digest = hash.update(nonce + message).digest('binary');
var hmac_digest = hmac.update(path + hash_digest, 'binary').digest('base64');
return hmac_digest;
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止所尝试的代码(以及它的许多变体):
收件人:JavaScript/Google Apps脚本
function getMessageSignature(url, request, nonce) {
// Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data))
//and base64 decoded secret API key
const secretApiKey = 'wdwdKswdKKewe23edeYIvL/GsltsGWbuBXnarcxZfu/9PjFbXl5npg==';
var secretApiKeyBytes = Utilities.base64Decode(secretApiKey);
var blob = Utilities.newBlob(secretApiKeyBytes);
var secretApiKeyString = blob.getDataAsString(); // POTENTIAL ERROR HERE?
var json = Utilities.jsonStringify(request);
var hash_digest = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256,
nonce + json);
var hmac_digest = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512,
url + hash_digest, secretApiKeyString); // POTENTIAL ERROR HERE?
var base64 = Utilities.base64Encode(hmac_digest);
return base64;
}
Run Code Online (Sandbox Code Playgroud)
当签名作为我的请求的一部分发送到服务器时,我总是从服务器收到错误消息:Invalid Key.
BTW:这是我想在JavaScript中使用的API:Kraken API
非常感谢任何提示或建议!
一个问题是querystring.stringify与 不同Utilities.jsonStringify(仅供参考,不推荐使用JSON.stringify)。
我相信这将是等效的:
function queryStringify(obj) {
var params = [];
for(var key in obj) {
if(Object.hasOwnProperty(key)) {
if(typeof key === 'string') {
params.push([key, obj[key]]);
} else {
obj[key].forEach(function(val) {
params.push([key, val]);
});
}
}
}
return params.map(function(param) {
return encodeURIComponent(param[0]) + '=' + encodeURIComponent(param[1]);
}).join('&');
}
Run Code Online (Sandbox Code Playgroud)
虽然我不确定这是否是您看到错误的原因。
| 归档时间: |
|
| 查看次数: |
2451 次 |
| 最近记录: |