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.

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

1 Answer 1


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)

  • 1
    $\begingroup$ 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. $\endgroup$
    – fgrieu
    Nov 14, 2018 at 16:58
  • $\begingroup$ 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. $\endgroup$ Nov 15, 2018 at 0:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.