Skip to content

Instantly share code, notes, and snippets.

@visualjeff
Created August 9, 2018 22:04
Show Gist options
  • Save visualjeff/ca00c48f3bfc95f6551302d47cb45040 to your computer and use it in GitHub Desktop.
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)
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
@visualjeff
Copy link
Author

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