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
-
stackoverflow.com/q/4083204/1820553kelalaka– kelalaka2020-06-11 20:28:01 +00:00Commented Jun 11, 2020 at 20:28
-
Generate 512 bits byte-by-byte (or word-by-word) and pack them into BigIntSeverin Pappadeux– Severin Pappadeux2020-06-11 20:43:54 +00:00Commented Jun 11, 2020 at 20:43
Add a comment
|
1 Answer
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)
);
4 Comments
Sam Mason
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 valuesMiguel Alorda
@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.Sam Mason
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 ~54Miguel Alorda
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.