Are there any SHA-256 javascript implementations that are generally considered trustworthy? [closed]

On https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest I found this snippet that uses internal js module:

async function sha256(message) {
    // encode as UTF-8
    const msgBuffer = new TextEncoder().encode(message);                    

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string                  
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex;
}

Note that crypto.subtle in only available on https or localhost – for example for your local development with python3 -m http.server you need to add this line to your /etc/hosts:
0.0.0.0 localhost

Reboot – and you can open localhost:8000 with working crypto.subtle.

Leave a Comment