Generate a 256 bit random number

Viewed 2985

I need to generate a 256 bits random unsigned number as a decimal string (with nearly zero probability of collision with anything generated earlier).

How to do this in JavaScript (in a browser)?

2 Answers

You can use the new JavaScript tools if you are not very limited:

function rnd256() {
  const bytes = new Uint8Array(32);
  
  // load cryptographically random bytes into array
  window.crypto.getRandomValues(bytes);
  
  // convert byte array to hexademical representation
  const bytesHex = bytes.reduce((o, v) => o + ('00' + v.toString(16)).slice(-2), '');
  
  // convert hexademical value to a decimal string
  return BigInt('0x' + bytesHex).toString(10);
}

console.log( rnd256() );

This code uses a loop to generate a 256 character long string of random binary digits, then converts it to a BigInt. You can then convert it to a string if you like, or whatever else you please.

    var temp = '0b';
    for (let i = 0; i < 256; i++) {
      temp += Math.round(Math.random());
    }

    const randomNum = BigInt(temp);
    console.log(randomNum.toString());
Related