简体   繁体   English

将Node.JS代码段转换为Javascript(Google Apps脚本)

[英]Convert Node.JS code snippet to Javascript (Google Apps Script)

I would like to convert the following Node.JS code snippet to JavaScript in order to run it in Google Apps Script: 我想将以下Node.JS代码段转换为JavaScript ,以便在Google Apps脚本中运行它:

From: Node.JS 来自: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;
}

This is the code I have tried so far (and many variations of it): 这是我到目前为止所尝试的代码(以及它的许多变体):

To: JavaScript / Google Apps Script 收件人: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;
}

When sending the signature as part of my request to the server, I always get the error message from the server: Invalid Key . 将签名作为我的请求的一部分发送到服务器时,我总是从服务器收到错误消息: Invalid Key

BTW: This is the API which I would like to use in JavaScript: Kraken API BTW:这是我想在JavaScript中使用的APIKraken API

I would appreciate any hint or suggestions very much!! 非常感谢任何提示或建议!

Solution: 解:

Use jsSHA ( https://github.com/Caligatio/jsSHA/ ) rather than Google App Script's functions. 使用jsSHA( https://github.com/Caligatio/jsSHA/ )而不是Google App Script的功能。 Create a new "jsSHA.gs" code file in Google App Script and copy/past in all the jsSHA optimised .js files from github. 在Google App Script中创建一个新的“jsSHA.gs”代码文件,并从github复制/过去所有jsSHA优化的.js文件。

function getKrakenSignature (path, postdata, nonce) {
  var sha256obj = new jsSHA ("SHA-256", "BYTES");
  sha256obj.update (nonce + postdata);
  var hash_digest = sha256obj.getHash ("BYTES");

  var sha512obj = new jsSHA ("SHA-512", "BYTES");
  sha512obj.setHMACKey (api_key_private, "B64");
  sha512obj.update (path);
  sha512obj.update (hash_digest);
  return sha512obj.getHMAC ("B64");
}

function getKrakenBalance () {
  var path = "/0/private/Balance";
  var nonce = new Date () * 1000;
  var postdata = "nonce=" + nonce;

  var signature = getKrakenSignature (path, postdata, nonce);

  var url = api_url + path;
  var options = {
    method: 'post',
    headers: {
      'API-Key': api_key_public,
      'API-Sign': signature
    },
    payload: postdata
  };

  var response = UrlFetchApp.fetch (url, options);

  // ERROR handling

  return response.getContentText ();
}

One problem is that querystring.stringify is not the same as Utilities.jsonStringify (which, FYI, is deprecated in favor of JSON.stringify ). 一个问题是querystring.stringifyUtilities.jsonStringify (其中,FYI,不赞成使用JSON.stringify )。

I believe that this will be equivalent: 我相信这将是相同的:

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('&');
}

Though I am not sure if that is the reason you are seeing your error. 虽然我不确定这是否是您看到错误的原因。

I noticed this nodejs to GS converter: https://www.npmjs.com/package/codegs 我注意到这个节点到GS转换器: https ://www.npmjs.com/package/codegs

Haven't got the chance to use it, but it claims to handle 'require'-statements. 没有机会使用它,但它声称处理'require'声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM