-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.py
97 lines (80 loc) · 2.01 KB
/
main.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
'''
Created on 07.09.2016
@author: Marius
'''
import random
max_PrimLength = 1000000000000
'''
calculates the modular inverse from e and phi
'''
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
'''
calculates the gcd of two ints
'''
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
'''
checks if a number is a prime
'''
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
def generateRandomPrim():
while(1):
ranPrime = random.randint(0,max_PrimLength)
if is_prime(ranPrime):
return ranPrime
def generate_keyPairs():
p = generateRandomPrim()
q = generateRandomPrim()
n = p*q
print("n ",n)
'''phi(n) = phi(p)*phi(q)'''
phi = (p-1) * (q-1)
print("phi ",phi)
'''choose e coprime to n and 1 > e > phi'''
e = random.randint(1, phi)
g = gcd(e,phi)
while g != 1:
e = random.randint(1, phi)
g = gcd(e, phi)
print("e=",e," ","phi=",phi)
'''d[1] = modular inverse of e and phi'''
d = egcd(e, phi)[1]
'''make sure d is positive'''
d = d % phi
if(d < 0):
d += phi
return ((e,n),(d,n))
def decrypt(ctext,private_key):
try:
key,n = private_key
text = [chr(pow(char,key,n)) for char in ctext]
return "".join(text)
except TypeError as e:
print(e)
def encrypt(text,public_key):
key,n = public_key
ctext = [pow(ord(char),key,n) for char in text]
return ctext
if __name__ == '__main__':
public_key,private_key = generate_keyPairs()
print("Public: ",public_key)
print("Private: ",private_key)
ctext = encrypt("Hello World",public_key)
print("encrypted =",ctext)
plaintext = decrypt(ctext, private_key)
print("decrypted =",plaintext)