Search code examples
react-nativecryptographycryptojspbkdf2

React Native SHA256 hasher with crypto-js


I am trying to use the crypto-js pbkdf2 algorithm in React Native. I swear I had it working, walked away from my computer and everything broke...

I am trying to create a password hash by await pbkdf2Sync(password, nonceData.salt, {hasher:cryptojs.algo.SHA256, iterations: 500, keySize: 32}).toString().substring(0,64); however cryptojs.algo.SHA256 is undefined.

I import everything like so

import pbkdf2Sync from 'crypto-js/pbkdf2'
import cryptojs from 'crypto-js/core'

but if I print cryptojs.algo to console I get that it only has SHA1, HMAC and PBKDF2.

How can I get the SHA256 algorithm to work?

I am using cryptojs 3.3.0 "crypto-js": "^3.3.0",


Solution

  • In 2023, most of modern browser supports Crypto API. If your target user using modern browser such as chrome and edge, just use Crypto API:

    const text = 'hello';
    
    async function digestMessage(message) {
      const msgUint8 = new TextEncoder().encode(message);                           // encode as (utf-8) Uint8Array
      const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);           // hash the message
      const hashArray = Array.from(new Uint8Array(hashBuffer));                     // convert buffer to byte array
      const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
      return hashHex;
    }
    
    const result = await digestMessage(text);
    console.log(result)
    

    Then you could verify the result via online sha256 tool.