Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate secure random string values in Javascript using cryto-random bytes
/** Generate secure random string values in Javascript using cryto-random bytes */
function randomHash (len) {
return Array.from(
window.crypto.getRandomValues(new Uint8Array(Math.ceil(len / 2))),
(b) => ("0" + (b & 0xFF).toString(16)).slice(-2)
).join("")
}
// Simple tests with various lengths
let n = 4
while (true) {
console.log("%s: %s", n, randomHash(n))
if (n === 256) break
n = n * 2
}
// 4: 156c
// 8: cce7c574
// 16: 26e5cb8a5d17e467
// 32: c9872b2cc69f01f0cb9b60141d9e23ea
// 64: 5b8b83dfab5462a36876c0726ec0ae77bec797ad97f7b220d1b8e90e5c46aa29
// 128: c5d78f8d129ea77660e27647473c2dc45f334d17e597e35add293b80a42e28e08c2596f2bb0ca07fc84139ecb0a5522dc8c79028fd3e3bfdfc8253cc2e41682b
// 256: 18350b6954beb9a606d716418aa1d9584aead14f381d5fa0c770f5a0c413ab28f3c0c4c6f428bc17e72183574977b129495c399ec82249fb477390eec89693c537018131e88b39a97df33713a5f87940ff01fcd03f09f4a125f4918b7481847ffdafe0f8a04fb63910ce58db92d667bd6cb4c8e42af19be4480e89c8c67c38ad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment