Debian Codegraph @

lib/Crypto/PublicKey/ElGamal.py

raw symbols SCIP
1 #
2 # ElGamal.py : ElGamal encryption/decryption and signatures
3 #
4 # Part of the Python Cryptography Toolkit
5 #
6 # Originally written by: A.M. Kuchling
7 #
8 # ===================================================================
9 # The contents of this file are dedicated to the public domain. To
10 # the extent that dedication to the public domain is not available,
11 # everyone is granted a worldwide, perpetual, royalty-free,
12 # non-exclusive license to exercise all rights associated with the
13 # contents of this file for any purpose whatsoever.
14 # No rights are reserved.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
20 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
21 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 # SOFTWARE.
24 # ===================================================================
25
26 __all__ = ['generate', 'construct', 'ElGamalKey']
27
28 from Crypto import Random
29 from Crypto.Math.Primality import ( generate_probable_safe_prime,
30 test_probable_prime, COMPOSITE )
31 from Crypto.Math.Numbers import Integer
32
33 # Generate an ElGamal key with N bits
34 def generate(bits, randfunc):
35 """Randomly generate a fresh, new ElGamal key.
36
37 The key will be safe for use for both encryption and signature
38 (although it should be used for **only one** purpose).
39
40 Args:
41 bits (int):
42 Key length, or size (in bits) of the modulus *p*.
43 The recommended value is 2048.
44 randfunc (callable):
45 Random number generation function; it should accept
46 a single integer *N* and return a string of random
47 *N* random bytes.
48
49 Return:
50 an :class:`ElGamalKey` object
51 """
52
53 obj=ElGamalKey()
54
55 # Generate a safe prime p
56 # See Algorithm 4.86 in Handbook of Applied Cryptography
57 obj.p = generate_probable_safe_prime(exact_bits=bits, randfunc=randfunc)
58 q = (obj.p - 1) >> 1
59
60 # Generate generator g
61 while 1:
62 # Choose a square residue; it will generate a cyclic group of order q.
63 obj.g = pow(Integer.random_range(min_inclusive=2,
64 max_exclusive=obj.p,
65 randfunc=randfunc), 2, obj.p)
66
67 # We must avoid g=2 because of Bleichenbacher's attack described
68 # in "Generating ElGamal signatures without knowning the secret key",
69 # 1996
70 if obj.g in (1, 2):
71 continue
72
73 # Discard g if it divides p-1 because of the attack described
74 # in Note 11.67 (iii) in HAC
75 if (obj.p - 1) % obj.g == 0:
76 continue
77
78 # g^{-1} must not divide p-1 because of Khadir's attack
79 # described in "Conditions of the generator for forging ElGamal
80 # signature", 2011
81 ginv = obj.g.inverse(obj.p)
82 if (obj.p - 1) % ginv == 0:
83 continue
84
85 # Found
86 break
87
88 # Generate private key x
89 obj.x = Integer.random_range(min_inclusive=2,
90 max_exclusive=obj.p-1,
91 randfunc=randfunc)
92 # Generate public key y
93 obj.y = pow(obj.g, obj.x, obj.p)
94 return obj
95
96 def construct(tup):
97 r"""Construct an ElGamal key from a tuple of valid ElGamal components.
98
99 The modulus *p* must be a prime.
100 The following conditions must apply:
101
102 .. math::
103
104 \begin{align}
105 &1 < g < p-1 \\
106 &g^{p-1} = 1 \text{ mod } 1 \\
107 &1 < x < p-1 \\
108 &g^x = y \text{ mod } p
109 \end{align}
110
111 Args:
112 tup (tuple):
113 A tuple with either 3 or 4 integers,
114 in the following order:
115
116 1. Modulus (*p*).
117 2. Generator (*g*).
118 3. Public key (*y*).
119 4. Private key (*x*). Optional.
120
121 Raises:
122 ValueError: when the key being imported fails the most basic ElGamal validity checks.
123
124 Returns:
125 an :class:`ElGamalKey` object
126 """
127
128 obj=ElGamalKey()
129 if len(tup) not in [3,4]:
130 raise ValueError('argument for construct() wrong length')
131 for i in range(len(tup)):
132 field = obj._keydata[i]
133 setattr(obj, field, Integer(tup[i]))
134
135 fmt_error = test_probable_prime(obj.p) == COMPOSITE
136 fmt_error |= obj.g<=1 or obj.g>=obj.p
137 fmt_error |= pow(obj.g, obj.p-1, obj.p)!=1
138 fmt_error |= obj.y<1 or obj.y>=obj.p
139 if len(tup)==4:
140 fmt_error |= obj.x<=1 or obj.x>=obj.p
141 fmt_error |= pow(obj.g, obj.x, obj.p)!=obj.y
142
143 if fmt_error:
144 raise ValueError("Invalid ElGamal key components")
145
146 return obj
147
148 class ElGamalKey(object):
149 r"""Class defining an ElGamal key.
150 Do not instantiate directly.
151 Use :func:`generate` or :func:`construct` instead.
152
153 :ivar p: Modulus
154 :vartype d: integer
155
156 :ivar g: Generator
157 :vartype e: integer
158
159 :ivar y: Public key component
160 :vartype y: integer
161
162 :ivar x: Private key component
163 :vartype x: integer
164 """
165
166 #: Dictionary of ElGamal parameters.
167 #:
168 #: A public key will only have the following entries:
169 #:
170 #: - **y**, the public key.
171 #: - **g**, the generator.
172 #: - **p**, the modulus.
173 #:
174 #: A private key will also have:
175 #:
176 #: - **x**, the private key.
177 _keydata=['p', 'g', 'y', 'x']
178
179 def __init__(self, randfunc=None):
180 if randfunc is None:
181 randfunc = Random.new().read
182 self._randfunc = randfunc
183
184 def _encrypt(self, M, K):
185 a=pow(self.g, K, self.p)
186 b=( pow(self.y, K, self.p)*M ) % self.p
187 return [int(a), int(b)]
188
189 def _decrypt(self, M):
190 if (not hasattr(self, 'x')):
191 raise TypeError('Private key not available in this object')
192 r = Integer.random_range(min_inclusive=2,
193 max_exclusive=self.p-1,
194 randfunc=self._randfunc)
195 a_blind = (pow(self.g, r, self.p) * M[0]) % self.p
196 ax=pow(a_blind, self.x, self.p)
197 plaintext_blind = (ax.inverse(self.p) * M[1] ) % self.p
198 plaintext = (plaintext_blind * pow(self.y, r, self.p)) % self.p
199 return int(plaintext)
200
201 def _sign(self, M, K):
202 if (not hasattr(self, 'x')):
203 raise TypeError('Private key not available in this object')
204 p1=self.p-1
205 K = Integer(K)
206 if (K.gcd(p1)!=1):
207 raise ValueError('Bad K value: GCD(K,p-1)!=1')
208 a=pow(self.g, K, self.p)
209 t=(Integer(M)-self.x*a) % p1
210 while t<0: t=t+p1
211 b=(t*K.inverse(p1)) % p1
212 return [int(a), int(b)]
213
214 def _verify(self, M, sig):
215 sig = [Integer(x) for x in sig]
216 if sig[0]<1 or sig[0]>self.p-1:
217 return 0
218 v1=pow(self.y, sig[0], self.p)
219 v1=(v1*pow(sig[0], sig[1], self.p)) % self.p
220 v2=pow(self.g, M, self.p)
221 if v1==v2:
222 return 1
223 return 0
224
225 def has_private(self):
226 """Whether this is an ElGamal private key"""
227
228 if hasattr(self, 'x'):
229 return 1
230 else:
231 return 0
232
233 def can_encrypt(self):
234 return True
235
236 def can_sign(self):
237 return True
238
239 def publickey(self):
240 """A matching ElGamal public key.
241
242 Returns:
243 a new :class:`ElGamalKey` object
244 """
245 return construct((self.p, self.g, self.y))
246
247 def __eq__(self, other):
248 if bool(self.has_private()) != bool(other.has_private()):
249 return False
250
251 result = True
252 for comp in self._keydata:
253 result = result and (getattr(self.key, comp, None) ==
254 getattr(other.key, comp, None))
255 return result
256
257 def __ne__(self, other):
258 return not self.__eq__(other)
259
260 def __getstate__(self):
261 # ElGamal key is not pickable
262 from pickle import PicklingError
263 raise PicklingError
264
265 # Methods defined in PyCrypto that we don't support anymore
266
267 def sign(self, M, K):
268 raise NotImplementedError
269
270 def verify(self, M, signature):
271 raise NotImplementedError
272
273 def encrypt(self, plaintext, K):
274 raise NotImplementedError
275
276 def decrypt(self, ciphertext):
277 raise NotImplementedError
278
279 def blind(self, M, B):
280 raise NotImplementedError
281
282 def unblind(self, M, B):
283 raise NotImplementedError
284
285 def size(self):
286 raise NotImplementedError