IoTHub device SASToken generation in react-native application

Naveen Kumar Jain S 1 Reputation point
2022-09-29T10:57:37.857+00:00

Hi,

In microsoft document (https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-dev-guide-sas?tabs=node#sas-token-structure) 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);  
hmac.update(stringToSign);  
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
    2022-09-30T09:45:47.913+00:00

    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));   
    hmac.update(stringToSign);   
    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
    2022-10-03T09:43:01.82+00:00

    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.

    https://javascript.plainenglish.io/using-core-node-js-modules-in-react-native-apps-e6002a33b6ff

    Thank you for following my question.