AirKetchup
AirKetchup

Reputation: 198

Javascript: Generate random integer of n bits

I want to generate a 512 bit integer for a DH private key. I looked around but cant find any javascript resources that show generating a random int of specific length

Upvotes: 1

Views: 908

Answers (1)

Miguel Alorda
Miguel Alorda

Reputation: 692

How about generating 16 random 32UInt as shown here. Theoretically, if you wanted the numbers all together, you could then do something like:

randomNumber = generatedArray.map((partialResult, value) => (partialResult << 32) + value));

However, be note the javascript MAX_SAFE_INTEGER is only 53 bits long.

Edit

As @SamMason commented, it should be reduce instead of map. Moreover, as the bit shift operator is only defined to work on 32bit values, we could just multiply by 2^32:

randomNumber = generatedArray.reduce(
    (partialResult, value) => partialResult * Math.pow(2,32) + value)
);

Upvotes: 1

Related Questions