javascriptsecure-random

Achieve new BigInteger(130, new SecureRandom()).toString(32) in JavaScript


I understand that we can use window.crypto to generate a secure random number, however window.crypto.getRandomValues() is using typedArray. May I know how can we achieve exactly this Java function in JavaScript:

new BigInteger(130, new SecureRandom()).toString(32)

Solution

  • You could generate four 32-bit numbers for a total of 128 - close to your Java maximum of 130 (the value specified to the constructor of BigInteger is the maximum number of bits, as stated in the docs), then convert them all to base 32, and finally join them together.

    function getSecureRandom() {
        // allocate space for four 32-bit numbers
        const randoms = new Uint32Array(4);
        // get random values
        window.crypto.getRandomValues(randoms);
        // convert each number to string in base 32, then join together
        return Array.from(randoms).map(elem => elem.toString(32)).join("");
    }
    

    The Array#from call is necessary because TypedArray.prototype.map returns another TypedArray, and a typed array cannot contain strings. We first convert the typed array randoms into a normal array, then call .map() on it.