Il metodo crypto.getRandomValues() è un’API CSPRNG (Cryptographically Secure PseudoRandom Number Generator) per cui il motore JS si appoggia al sistema operativo, che raccoglie entropia da vari eventi non prevedibili (movimenti mouse, latenza di rete, interrupt hardware, rumore dei circuiti, ecc.), è progettato per resistere ad attacchi predittivi. Gli output sono praticamente indistinguibili dal vero caso uniforme su 8 bit (0–255).
function cifraCasuale(zero) {
const array = new Uint8Array(1);
crypto.getRandomValues(array); // valori tra 0 e 255
return (zero)? array[0] % 10 : (array[0] % 9) + 1; // cifra tra 0 e 9 o tra 1 e 9
}
var estr = "" + cifraCasuale(false);
while (Math.random()<0.4) estr += cifraCasuale(true);