javascript - 海妖网站 API : Generate the message signature in AngularJS

标签 javascript angular encoding cryptography cryptojs

我正在尝试学习 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/

相关文章:

c# - 如何最好地读取和 UTF-8 解码字节缓冲区?

swift - Foundation 的字符串编码不是网站所期望的

javascript - 空字符串+变量: why?

cordova - ionic 服务找不到模块 'reflect-metadata'

typescript - Angular2 文档生成器

Angular 6 导入功能模块失败——装饰器不支持函数调用

java - 如何使用 JSON/JQUery 向外部网站提交数据并获取结果并显示在我的 JSP 页面中

javascript - ajax 更新后 Jquery masonary 格式更改

javascript - 2 张具有相同 src 的图像,一张渲染,一张不渲染。如何?

python - 在 python 中处理非 ascii 代码字符串