1

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

AirKetchup
  • 198
  • 1
  • 10

1 Answers1

1

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)
);
Miguel Alorda
  • 623
  • 5
  • 13
  • isn't that `reduce` rather than `map`? even then it doesn't do the right thing, intermediate values overflow and wrap around as the shift operator is defined to work on 32bit values – Sam Mason Jun 12 '20 at 22:26
  • @SamMason True, it should be `reduce`. And thank you, I did not know about the 32bit limitation. I guess I could just multiply by `2^16`. – Miguel Alorda Jun 13 '20 at 10:05
  • wouldn't that be 2**32 given that you talked about 32bit uints initially? javascript also doesn't have arbitrary precision numbers, so this is going to be little better than doing `Math.random() * 2**512` (only a "little" because you might get a CSPRNG) but why generate 512 bits to throw away all but top ~54 – Sam Mason Jun 13 '20 at 17:58
  • Yes, it should be 2**32, thank you. I just pointed out this method would theretically work. However, as you mention, only ~54 bits could actually be used because of Javascript's precision limitation. – Miguel Alorda Jun 13 '20 at 18:42