How to Hash Buffer with Expo for an array

Please provide the following:

  1. SDK Version:v39.0.0.
  2. Platforms(Android/iOS/web/all): all

Hello,

Expo now provides a hashing method but only accepts String types for input.

Nodejs provides hashing of buffers/strings/arrays and can return the hashed value as a buffer as well .

The issue I am having is that I need to hash a buffer( uint8array ) in my app with sha256 . So I must find a way to convert it to a string, this causes issues because if I convert the buffer to anything else ex.( hexString,base64 ) my hash result is not equivalent to the exact value that nodejs crypto would provide.

have also tried converting the buffer to utf-8/16 strings but this causes issues because the chars in this format can have multiple bytes( issues with the number being above 127 ). So this path was incorrect as well.

My hashes must be equivalent to the traditional nodejs createHash() results.

I am hitting a wall on this issue and not not find a way around it.

Any way to handle it ?

Many thanks

To complete my question, I am looking for a snipet to replace the following code without the crypto import and be able to hash Uint8Array.


export async function sha256(data) {
  const hash = crypto.createHash('sha256');
  hash.update(data); // data here is a Uint8Array !
  const digest = hash.digest();
}

As reminder, expo-crypto handles only string and not Unit8Array :frowning:

Here is a possible answer that work fine :

  • let’s use the web crypto API, so no need to import lib crypto
// Web Crypto API : message could be text or Unit8Array

const SHA256digest = async (message) => {            
 const crypto = (self.crypto || self.msCrypto); // to cope with IE 11
 let msgUint8 = message; 
 if ( typeof message === 'string' ) { //for text message
   msgUint8 = new TextEncoder().encode(message);      
 } 

 const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
 const hashArray = Array.from(new Uint8Array(hashBuffer));
 return hashArray;
}

So it’s possible to call the function like this:

  const digest = await SHA256digest(data);

It does not use expo-crypto but does the job on browser side.
I’m still motivated by a solution using expo-crypto