IoT Hub SAS Tokens Node JS Crypto error

时间:2016-04-07 10:28:05

标签: azure cryptography azure-iot-hub

I have a problem when using SAS tokens to connect with IoT Hub. In the example from Microsoft, there is an example code for NodeJS to create a SAS token with crypto. However, when I use this code in NodeJS, it throws this error.

However, I did everything in the tutorial and I cannot see anything missing. The example code is the following:

// Creating SAS token
var crypto = require('crypto');

var generateSasToken = function (resourceUri, signingKey, policyName, expiresInMins) {
    resourceUri = encodeURIComponent(resourceUri.toLowerCase()).toLowerCase();

    // Set expiration in seconds
    var expires = (Date.now() / 1000) + expiresInMins * 60;
    expires = Math.ceil(expires);
    var toSign = resourceUri + '\n' + expires;

    // using crypto
    var decodedPassword = new Buffer(signingKey, 'base64').toString('binary');
    const hmac = crypto.createHmac('sha256', decodedPassword);
    hmac.update(toSign);
    var base64signature = hmac.digest('base64');
    var base64UriEncoded = encodeURIComponent(base64signature);

    // construct autorization string
    var token = "SharedAccessSignature sr=" + resourceUri + "&sig=" 
    * base64UriEncoded + "&se=" + expires;
    if (policyName) token += "&skn=" + policyName;
     console.log("signature:" + token);
    return token;
};

I hope that someone can help me with this mystery haha..

1 个答案:

答案 0 :(得分:0)

屏幕截图中显示的错误表明共享访问签名的一部分丢失或无法解析。

我可以在您的代码中看到几件事:

  1. 连接字符串以创建令牌时,*应为+

  2. 您生成hmac哈希的方式:我们不会在包含密码的base64编码缓冲区上使用' toString(' binary')(不应该' t如果您尝试使用browserify,则会出现节点问题:

  3. function hmacHash(password, stringToSign) {
      var hmac = crypto.createHmac('sha256', new Buffer(password, 'base64'));
      hmac.update(stringToSign);
      return hmac.digest('base64');
    }
    

    (参考:authorization.js

    从错误的屏幕截图看,您似乎已经在使用node.js SDK了,您是否尝试使用Device SDK或{{3}的SharedAccessSignature.create(...)方法(取决于你想要实现的目标?)

    它将替换您发布的代码:

    // compute expiry value
    var expires = (Date.now() / 1000) + expiresInMins * 60;
    expires = Math.ceil(expires);
    // generate SAS token
    var sas = SharedAccessSignature.create(resourceUri, policyName, signingKey, expires);
    // from then you can create a client object:
    var client = Client.fromSharedAccessSignature(sas.toString());