Javascript Crypto API / Random Values

Date: 2021-11-18

Web Crypto API

function randomId(): string {
  const uint32 = window.crypto.getRandomValues(new Uint32Array(1))[0];
  return uint32.toString(16);
}
function cryptoRand(max) {
    if (max <= 0) return 0;

    // Uint32 voor maximale range
    const array = new Uint32Array(1);
    crypto.getRandomValues(array);

    // modulo-bias vermijden:
    const limit = Math.floor(0xFFFFFFFF / max) * max;
    if (array[0] >= limit) {
        // opnieuw proberen (recursief)
        return cryptoRand(max);
    }

    return array[0] % max;
}
56430cookie-checkJavascript Crypto API / Random Values