-
Notifications
You must be signed in to change notification settings - Fork 1
/
elGamal.py
376 lines (245 loc) · 9.71 KB
/
elGamal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ressources.prng as prng
import ressources.utils as ut
import ressources.bytesManager as bm
import ressources.interactions as it
import ressources.multGroup as multGroup
import ressources.config as config
import random as rd
#############
# ElGamal encryption consists of three components: the key generator, the encryption algorithm, and the decryption algorithm.
# Like most public key systems, the ElGamal cryptosystem is usually used as part of a hybrid cryptosystem where
# the message itself is encrypted using a symmetric cryptosystem and ElGamal is then used to encrypt only the symmetric key.
############
def generator(p: int, q: int, r: int = 2):
"""
Find a generator g such as g order is q (Sophie Germain prime) with p = 2q + 1.
That's a generator for Gq. Not Zp* and any other subgroup. Very important point.
Shnorr group of r.
https://en.wikipedia.org/wiki/Schnorr_group
Avoid commons attacks.
"""
assert p == r * q + 1
while 1:
# Choose a random quadratic residues, thus is multiplicative order will be q.
# Without 0 and 1 to keep only legender symbol = 1 results
e = rd.randrange(2, p)
g = ut.square_and_multiply(e, r, p)
# We must avoid g=2 because of Bleichenbacher's attack described
# in "Generating ElGamal signatures without knowning the secret key",
# 1996
if g in (1, 2):
continue
# Discard g if it divides p-1
if (p - 1) % g == 0:
continue
# g^{-1} must not divide p-1 because of Khadir's attack
# described in "Conditions of the generator for forging ElGamal
# signature", 2011
if (p - 1) % multGroup.inv(g, p) == 0:
continue
# Found a good candidate
return g
def isEasyGeneratorPossible(s: tuple):
"""
Return True is it's possible to generate easly a generator.
"""
p, _ = s
return p % 3 == 2 and (p % 12 == 1 or p % 12 == 11)
#############################################
########### - Key Generation - ##############
#############################################
def key_gen(
n: int = 2048,
primeFount=True,
easyGenerator: bool = False,
randomFunction=None,
saving=False,
Verbose=False,
) -> tuple:
"""
ElGamal key generation.
n: number of bits for safe prime generation.\n
primeFount = prime number's fountain used, put tuple of primes into this variable.\n
easyGenerator: generate appropriated safe prime number according to quadratic residues properties.\n
randomFunction: prng choosen for random prime number generation (default = randbits from secrets module).
saving: True if you want to save the private key to a file.
"""
if not primeFount:
if Verbose:
print(f"Let's try to generate a safe prime number of {n} bits.")
s = prng.safePrime(n, randomFunction, easyGenerator)
else:
primeFount = it.extractSafePrimes(n, False, Verbose)
s = primeFount
p, q = s # safe_prime and Sophie Germain prime
if Verbose:
print(f"Let's find the generator for p: {p} , safe prime number.\n")
# Generate an efficient description of a cyclic group G, of order q with generator g.
if easyGenerator:
# https://en.wikipedia.org/wiki/Quadratic_residue#Table_of_quadratic_residues
if Verbose:
print("Easy generator => gen = 12 (condition in prime generation) or (4, 9) (for every prime)")
gen = rd.choice([12, 4, 9])
else:
gen = generator(p, q)
if Verbose:
print(f"generator found: {gen}\n")
# The description of the group is (g, q, p)
# When p=2q+1, they are the exact same group as Gq.
# The prime order subgroup has no subgroups being prime.
# This means, by using Gq, you don't have to worry about an adversary testing if certain numbers are quadratic residues or not.
# The message space MUST be restrained to this prime order subgroup.
x = rd.randrange(1, p - 1) # gcd(x, p) = 1
h = ut.square_and_multiply(gen, x, p)
# The private key consists of the values (G, x).
private_key = (p, gen, x)
if saving:
it.writeKeytoFile(private_key, "private_key", config.DIRECTORY_PROCESSING, ".kpk")
if Verbose:
print("\nYour private key has been generated Alice, keep it safe !")
# The public key consists of the values (G, q, g, h).
# But we saved only (p, g, h) cause q = (p-1)//2
public_key = (p, gen, h)
if saving:
public_key = it.writeKeytoFile(public_key, "public_key", config.DIRECTORY_PROCESSING, ".kpk")
if Verbose:
print("\nThe public key has been generated too: ", end="")
it.prGreen(public_key)
if not saving:
return (public_key, private_key)
#############################################
########### - Encryption - ##############
#############################################
def encrypt(M: bytes, publicKey, saving: bool = False):
assert isinstance(M, (bytes, bytearray))
p, g, h = publicKey
def process(m):
y = rd.randrange(1, p - 1)
# shared secret -> g^xy
c1 = ut.square_and_multiply(g, y, p)
s = ut.square_and_multiply(h, y, p)
c2 = (m * s) % p
return (c1, c2)
Mint = bm.bytes_to_int(M)
if Mint < p:
# That's a short message
m = Mint
e = process(m)
else:
# M is a longer message, so it's divided into blocks
# You need to choose a different y for each block to prevent
# from Eve's attacks.
size = (it.getKeySize(publicKey) // 8) - 1
e = [process(bm.bytes_to_int(elt)) for elt in bm.splitBytes(M, size)]
if saving:
e = it.writeKeytoFile(e, "encrypted", config.DIRECTORY_PROCESSING, ".kat")
return e
#############################################
########### - Decryption - ##############
#############################################
def decrypt(c, privateKey: tuple, asTxt=False):
"""
Decryption of given ciphertext 'c' with secret key 'privateKey'.
Return bytes/bytearray or txt if asTxt set to 'True'.
"""
p, _, x = privateKey
def process(cipherT):
c1, c2 = cipherT
s1 = ut.square_and_multiply(c1, p - 1 - x, p)
# This calculation produces the original message
m = (c2 * s1) % p
return bm.mult_to_bytes(m)
if isinstance(c, list):
decrypted = [process(elt) for elt in c]
r = bm.packSplittedBytes(decrypted)
else:
r = process(c)
if asTxt:
return r.decode()
return r
#############################################################
################ - Signature scheme - #######################
#############################################################
def signing(M: bytes, privateK: tuple = None, saving: bool = False, Verbose: bool = False):
"""
Signing a message M (bytes).
"""
from ..hashbased import hashFunctions as hashF
# y choosed randomly between 1 and p-2 with condition than y coprime to p-1
if not privateK:
privateK = it.extractKeyFromFile("private_key")
p, g, x = privateK
size = it.getKeySize(privateK)
# M = bm.fileToBytes(M)
# M = "Blablabla".encode()
if Verbose:
print("Hashing in progress...")
hm = hashF.sponge(M, size)
# #base64 to int
hm = bm.bytes_to_int(bm.mult_to_bytes(hm))
if Verbose:
print("Hashing done.\n")
p1 = p - 1
k = rd.randrange(2, p - 2)
while not ut.coprime(k, p1):
k = rd.randrange(2, p - 2)
if Verbose:
print(f"Your secret integer is: {k}")
s1 = ut.square_and_multiply(g, k, p)
s2 = (multGroup.inv(k, p1) * (hm - x * s1)) % p1
# In the unlikely event that s2 = 0 start again with a different random k.
if s2 == 0:
if Verbose:
print("Unlikely, s2 is equal to 0. Restart signing...")
signing(M, privateK, saving, Verbose)
else:
sign = (s1, s2)
if saving:
sign = it.writeKeytoFile(sign, "elG_signature")
return sign
def verifying(M: bytes, sign: tuple, publicKey: tuple = None):
"""
Verify given signature of message M with corresponding public key's.
"""
assert isinstance(M, (bytes, bytearray))
from ..hashbased import hashFunctions as hashF
if not publicKey:
publicKey = it.extractKeyFromFile("public_key")
p, g, h = publicKey
size = it.getKeySize(publicKey)
hm = hashF.sponge(M, size)
hm = bm.bytes_to_int(bm.mult_to_bytes(hm))
if not isinstance(sign, tuple):
b64data = sign
sign = it.getIntKey(b64data[1:], b64data[0])
s1, s2 = sign
if (0 < s1 < p) and (0 < s2 < p - 1):
test1 = (ut.square_and_multiply(h, s1, p) * ut.square_and_multiply(s1, s2, p)) % p
test2 = ut.square_and_multiply(g, hm, p)
if test1 == test2:
return True
return False
raise ValueError
#############################################################
################ - Logarithmic attack - #####################
#############################################################
def delog(publicKey, encrypted=None, asTxt=False, method=1):
"""
Retrieve private key with publicKey.
And if you get the encrypted message, thus you can decrypt them.
"""
def dlog_get_x(publicKey):
"""
Find private key using discrete logarithmic method.
"""
# PublicKey format: (p, q, gen, h)
p, g, h = publicKey
x = ut.discreteLog(g, h, p, method)
# Same format as private key
return (p, g, x)
private_Key = dlog_get_x(publicKey)
if encrypted is None:
return private_Key
return decrypt(encrypted, private_Key, asTxt)