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

2

1 Answer 1

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)
);
Sign up to request clarification or add additional context in comments.

4 Comments

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
@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.
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.