cd23639
--- lib/Crypto/PublicKey/ElGamal.py
cd23639
+++ lib/Crypto/PublicKey/ElGamal.py
cd23639
@@ -153,33 +153,33 @@ def generate(bits, randfunc, progress_fu
cd23639
         if number.isPrime(obj.p, randfunc=randfunc):
cd23639
             break
cd23639
     # Generate generator g
cd23639
-    # See Algorithm 4.80 in Handbook of Applied Cryptography
cd23639
-    # Note that the order of the group is n=p-1=2q, where q is prime
cd23639
     if progress_func:
cd23639
         progress_func('g\n')
cd23639
     while 1:
cd23639
+        # Choose a square residue; it will generate a cyclic group of order q.
cd23639
+        obj.g = pow(number.getRandomRange(2, obj.p, randfunc), 2, obj.p)
cd23639
+
cd23639
         # We must avoid g=2 because of Bleichenbacher's attack described
cd23639
         # in "Generating ElGamal signatures without knowning the secret key",
cd23639
         # 1996
cd23639
-        #
cd23639
-        obj.g = number.getRandomRange(3, obj.p, randfunc)
cd23639
-        safe = 1
cd23639
-        if pow(obj.g, 2, obj.p)==1:
cd23639
-            safe=0
cd23639
-        if safe and pow(obj.g, q, obj.p)==1:
cd23639
-            safe=0
cd23639
+        if obj.g in (1, 2):
cd23639
+            continue
cd23639
+
cd23639
         # Discard g if it divides p-1 because of the attack described
cd23639
         # in Note 11.67 (iii) in HAC
cd23639
-        if safe and divmod(obj.p-1, obj.g)[1]==0:
cd23639
-            safe=0
cd23639
+        if (obj.p - 1) % obj.g == 0:
cd23639
+            continue
cd23639
+
cd23639
         # g^{-1} must not divide p-1 because of Khadir's attack
cd23639
         # described in "Conditions of the generator for forging ElGamal
cd23639
         # signature", 2011
cd23639
         ginv = number.inverse(obj.g, obj.p)
cd23639
-        if safe and divmod(obj.p-1, ginv)[1]==0:
cd23639
-            safe=0
cd23639
-        if safe:
cd23639
-            break
cd23639
+        if (obj.p - 1) % ginv == 0:
cd23639
+            continue
cd23639
+
cd23639
+        # Found
cd23639
+        break
cd23639
+
cd23639
     # Generate private key x
cd23639
     if progress_func:
cd23639
         progress_func('x\n')