我正在尝试学习 Angular2,作为第一个练习,我想从 Kraken.com API 检索数据。 (我知道,我本可以选择更简单的东西 :)
好吧,对于“公共(public)”调用,它工作得很好。现在我正在尝试调用“私有(private)”方法。 (那些需要进行身份验证)
正如这里所说: https://www.kraken.com/help/api
预期的签名是:
API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
所以我正在尝试生成那个...没有成功...我不断收到此错误消息:
Kraken API returned an error: API:Invalid nonce
但我很确定我的随机数是正确的,所以我宁愿认为它与数据加密有关。
我找到了 here一个应该完成这项工作的功能,但我不能在我的 Angular 项目中“按原样”使用它。
/**
* This method returns a signature for a request as a Base64-encoded string
* @param {String} path The relative URL path for the request
* @param {Object} request The POST body
* @param {Integer} nonce A unique, incrementing integer
* @return {String} The request signature
*/
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;
}
这是我的代码:
private getMessageSignature(path: string, request: any, nonce: number) {
//API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key
var message = this.querystring.stringify(request);
var secret = this.CryptoJS.enc.Base64.parse(this.config.secret);
var hash_digest = this.CryptoJS.SHA256(nonce + message);
var hmac = this.CryptoJS.HmacSHA512(path + hash_digest, secret).toString(this.CryptoJS.enc.Base64);
return hmac;
}
最佳答案
问题很可能是 path + hash_digest
,这是一种类型不匹配,会导致奇怪的结果,因为 hash_digest
将被十六进制编码,不会用于其二进制表示形式。
以下可能有效:
var hmac = this.CryptoJS.HmacSHA512(path + hash_digest.toString(this.CryptoJS.enc.Latin1), secret).toString(this.CryptoJS.enc.Base64);
但以下是更好的选择:
var hmacHasher = this.CryptoJS.algo.HMAC.create(this.CryptoJS.algo.SHA512, secret);
hmacHasher.update(path);
hmacHasher.update(hash_digest);
var hmac = hmacHasher.finalize().toString(this.CryptoJS.enc.Base64);
关于javascript - 海妖网站 API : Generate the message signature in AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42784299/