# Diffie-Hellman server/client generated secret size

So I have implemented a client and a server performing Diffie-Hellmann, however sometimes the symmetric key is not valid?

Example:

• Prime: 23
• Primitive root: 5
• client secret: 14
• server secret: 16

This results in a faulty generated symmetric key.

1. Client shared key: $${5^{14}\mod 23}=13$$
2. Server shared key: $${5^{16}\mod 23}=3$$
3. Client "symmetric key": $${3^{14}\mod 23}=4$$
4. Server "symmetric key": $${13^{16}\mod 23}=8$$

So we can conclude that the provided arguments resulted in a faulty Diffie-Hellman since $$4\ne8$$.

What is the rule for the pseudorandom generated secret keys of the server and the client?

Javascript is used for the calculations, e.g. 13**16%23.

• WolframAlpha disagrees with $13^{16}\bmod 23$ being $8$ and instead claims the consistent $4$. I suppose a mistake happened there in the calculations leading to 8? May 22, 2020 at 14:19
• I use JavaScript, running 13**16%23 in the browser console returns 8. If JavaScripts is inaccurate, then I have lost at the very least an hour because of it May 22, 2020 at 14:25
• You need 60 bits to represent $13^{16}$ and JavaScript only knows doubles which have 52bit precision, so chances are JS rounded the result, then reduced and yielded 8 to you. May 22, 2020 at 14:28
• @JonasGrønbek Are you using BigInteger or Number? May 22, 2020 at 14:28
• Jesus Christ, will you post as answer @SEJPM? May 22, 2020 at 14:29

In this particular case the issue is that JS has no integer type, so everything is stored as a double. In particular the last calculation $$13^{16}$$ would yield a 60-bit integer which JS computes as ordered. However double only has 52 bits for the mantissa and so can't possibly contain the full value. So JS rounds. Then it takes the rounded number and applies the $$\bmod 23$$ reduction yielding some unrelated value to the one you intended to compute.