# Choosing good entropy $g$ and $p$ for a classic Diffie-Hellman Key exchange

When selecting $$g$$ and $$p$$ for the Diffie-Hellman modular exponentiation:

$$s= g^x \bmod p$$

Which pairs of $$g$$ and $$p$$ are considered good nowadays, are recommended by bibliography?

What I try to do is to write a simple Python script that chain calculates Diffie-Hellman Modular exponentiation:

def dh_public(secret):
g=5;p=23 //@todo select better values

return g**secret % p


For now, I have REALLY POORLY selected values but I want standardized and tested values for calculating a Diffie Hellman key exchange. As far as I know, both $$g$$ and $$p$$ should be primes.

• There is no specific reason why $g$ must be a prime Nov 14, 2018 at 14:44
• $p$ should be a prime and $g$ a primitive root Nov 14, 2018 at 14:53
• IANA has a registery of them Nov 14, 2018 at 15:00
• @YoussefElHousni: $g$ needn't be a primitive root; it must generate a subgroup which has a size with a large prime factor Nov 14, 2018 at 15:03
• @poncho I agree. $g$ only needs to be of order multiple of a large enough prime. Nov 14, 2018 at 15:36

The most commonly used values are in this RFC; it includes groups that range from 1536 to 8192 bits; the size 2048 is actually the most common.

The properties of these groups include:

• The modulus is chosen using a 'nothing up my sleeve' method (and hence is unlikely to be specifically chosen to be especially vulnerable)

• The modulus has the high 32 bits and the low 32 bits all set; this can be useful for some modmul algorithms

• It has $$g=2$$; this can make the initial computation of $$g^x \bmod p$$ rather more efficient

• The order of the subgroup generated by $$g$$ is a prime of size $$(p-1)/2$$; a size which is quite sufficient for security

DannyNiu's reference to the IANA TLS groups (actually, the groups 256-260; the others are various elliptic curves which aren't what you are asking about) are another set; they're actually generated using the same procedure (and share the above properties), but are deliberately slightly different (to avoid potential factor-based style attacks against the original group)

• Addition: the fragment g**secret % p must be changed to pow(g, secret, p) for the code to work with sizable arguments. Making it secure against side-channel attacks is uh, much harder.
– fgrieu
Nov 14, 2018 at 16:58
• Well I do not want to mmake it ultra secure just to do some tests/research on chaining Diffie Hellman calculations on a Rachet tree Implementation. Nov 15, 2018 at 0:07