IoTHub device SASToken generation in react-native application

Naveen Kumar Jain S 1 Reputation point


In microsoft document ( the method to generate the Azure IoTHub device SAS Token is provided for Node.js platform using crypto. But the same method is failing in react-native application.

Can anyone suggest a method/library which will work on react-native application?

Note: I have tried using react-js npm module using below method

import CryptoJS from 'crypto-js'  
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, deviceKey);  
var hash = CryptoJS.enc.Base64.stringify(hmac.finalize());  
 console.log('hash: ', hash)  

But the signature generated with above method is failing to authenticate with IoTHub device.

Azure IoT Hub
Azure IoT Hub
An Azure service that enables bidirectional communication between internet of things (IoT) devices and applications.
1,136 questions
{count} votes

2 answers

Sort by: Most helpful
  1. chbeier 1,866 Reputation points

    Hello @Naveen Kumar Jain S ,

    Most likely, it is an encoding problem of the key and URI. You can try the following code:

    var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, CryptoJS.enc.Base64.parse(deviceKey));   
    var hash = encodeURIComponent(CryptoJS.enc.Base64.stringify(hmac.finalize()));  
    console.log("hash: ", hash);  
    1 person found this answer helpful.
    0 comments No comments

  2. Naveen Kumar Jain S 1 Reputation point

    Hi @chbeier ,

    Actually I had also tried this combination where Base64 encoded deviceKey is used for HmacSHA256 generation.

    I was able to generate device SAS token which is correctly authenticated with IoTHub by following the below blog.

    Thank you for following my question.