4

I'm trying to implement a diffie-hellman key exchange. Let's say I found a large prime number p - how can I find a generator g?

Restricted by the multiprecision library that I have to use, only a few basic operations (+, *, -, /, pow, modExp, modMult, mod, gcd, isPrime, genRandomPrime, genRandomBits, and a few more) are available.

Would it work to look for a safe prime q, so that every number n for which gcd(n,q) == 1 should be a generator, right?

user66875
  • 2,772
  • 3
  • 29
  • 55

3 Answers3

3

You basically answered your question. Just the test gcd(n,q)==1 is not necessary since q is prime. It means that any number n, such that n < q does not have common factor with q and gcd(n,q) will always output 1.

You can check whether q=2p + 1 is prime number. If so, then ord(Zq) = q-1 = (2p+1)-1 = 2p. Since ord(x) | ord(Zq) for every x in Zq ord(x)=2 or ord(x)=p or ord(x)=2p. Thus you just need to check whether your randomly chosen element x from {2,...,q-1} is of order 2. If not then it is of order p or 2p and you can use it as a generator.

Marek Klein
  • 1,410
  • 12
  • 20
3

As a rule, don't ask programmers questions about cryptography. Cryptography is subtle and, as a result, difficult in invisible ways that lead readily to self-deception about one's own competence. Instead, ask cryptographers (many of which are also programmers). Stack Exchange has a cryptography board, where this question has already been answered.

https://crypto.stackexchange.com/questions/29926/what-diffie-hellman-parameters-should-i-use

I could quibble with the advice there, but it's basically sound. Unless you really want to learn the relevant mathematics, I'd defer to authorities; they're cited in the answer above.

As to the mathematics question you ask, here's a tiny introduction. The multiplicative group modulo a prime p has size p-1. (See Fermat's Little Theorem.) The order of any element must divide p-1. The most favorable case is where p-1=2q, where q is also prime.

Community
  • 1
  • 1
eh9
  • 7,340
  • 20
  • 43
  • If you mean by maximal order of an element number q-1 then it is not true that there is no element of maximal order. Imagine simple multiplicative group Z mod 11. ord(2) is 10. – Marek Klein Nov 16 '16 at 12:29
  • @MarekKlein I removed the offending claim. I shouldn't do math when I'm distracted. – eh9 Nov 18 '16 at 23:42
1

You've already gotten the ritual admonishment not to roll your own crypto if you care at all about your security, so here's how to find a generator mod a safe prime q. A number g in the closed range [2, q - 2] is a generator if and only if g^((q-1)/2) != 1 mod q, which you should compute with the standard algorithm for modular exponentiation. Choose random values of g until one passes the test.

David Eisenstat
  • 64,237
  • 7
  • 60
  • 120