Created
August 9, 2018 22:04
-
-
Save visualjeff/ca00c48f3bfc95f6551302d47cb45040 to your computer and use it in GitHub Desktop.
Generating a good nonce in the browser to prevent replay (in Javascript SPA's)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const crypto = crypto.subtle; | |
async function sha256(message) { | |
const msgBuffer = new TextEncoder('utf-8').encode(message); // encode as UTF-8 | |
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer); // hash the message | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert ArrayBuffer to Array | |
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join(''); // convert bytes to hex string | |
return hashHex; | |
} | |
let randomNumber = window.crypto.getRandomValues(new Uint32Array(1)); //Generate randomNumber and store in local storage. | |
sha256(randomNumber).then(hash => console.log(hash)); //Use hash value of randomNumber for the nonce |
A work around for test / development would be to test if crypto.subtle is undefined. If so short circuit and return defaultNonce for a nonce value.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE: This crypto.subtle will be undefined unless you working within the context of a proper hostname/URL.