Crypto API
randomUUID()
Generate random UUID in browser console
this.crypto.randomUUID(); // '7ed9244d-6464-4ed7-a0a0-800a5e492641'
getRandomValues()
Get cryptographically strong random values
- To guarantee enough performance, implementations are not using a truly random number generator, but they are using a pseudo-random number generator seeded with a value with enough entropy
- The pseudo-random number generator algorithm (
PRNG) may vary across user agents, but is suitable for cryptographic purposes
Syntax
Argument
Takes integer-based typed array as an argument
- one of:
Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,BigInt64Array,BigUint64Array(but notFloat32ArraynorFloat64Array)
getRandomValues(typedArray)
Example
const array = new Uint32Array(10); self.crypto.getRandomValues(array); for (const num of array) { console.log(num); }
Return Value
All elements in the array will be overwritten with random numbers
typedArrayis modified in-place, and no copy is made
Security
Although more random than Math.random(), it's not guaranteed to be running in a secure context
MDN recommends to use
generateKey()instead when random value must be used as an encryption key