JSFiddle - React, Tailwind, and code Playground
by David Marshall
JavaScript
async function sha512(message) {
console.log('to hash:',message)
// encode as UTF-8
const msgBuffer = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest("SHA-512", 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;
}
// Initialize variables
let state = 97 // Initial state (seed)
let entropy_input-'sdafe' // Entropy input obtained from a secure source
let nonce = 0 // Nonce (optional, used for additional security)
let personalization_string = 'test' // Personalization string (optional, used to customize the generator)
// Reseed the generator with new entropy
function reseed(entropy) {
sha512(state || entropy || nonce || personalization_string).then(h=>state = h)
}
// Generate pseudorandom output
function generate(output_length) {
let pseudorandom_output = ""
while (pseudorandom_output.length < output_length) {
sha512(state).then(h=>{
state=h
pseudorandom_output += state
})
}
return pseudorandom_output
}
// Usage example:
reseed(entropy_input)
let random_bits = generate(2)
console.log(random_bits)