-
Notifications
You must be signed in to change notification settings - Fork 0
/
my_RSA
118 lines (97 loc) · 2.59 KB
/
my_RSA
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
"""https://www.khanacademy.org/computing/computer-science/cryptography
https://www.youtube.com/watch?v=qfgYfyyBRcY
https://www.youtube.com/watch?v=kYasb426Yjk"""
import prime_chooser
import Sieve_of_Eratosthenes
import math
p=int()
q=int()
e=int()
d=int() #d= mod inverse of e
n=int()
phi=int()
def make_pl():
"""makes the primes list. Used in find_k_d_e()."""
primes_list=list(Sieve_of_Eratosthenes.sieve_using_set_and_ranges(100000))
primes_list.sort()
while primes_list[0]<math.log(n,2):
del(primes_list[0])
return primes_list
def choose_primes_n_phi():
"""this is totally good"""
global p
global q
global n
global phi
q=prime_chooser.prime_Chooser(2**124)
p=prime_chooser.prime_Chooser(2**120)
n=q*p
phi=((p-1)*(q-1))
return
def extendedEuclid(a, b):
"""return a tuple of three values: x, y and z, such that x is
the GCD of a and b, and x = y * a + z * b
https://www.youtube.com/watch?v=kYasb426Yjk"""
if a == 0:
return b, 0, 1
else:
g, y, x = extendedEuclid(b % a, a)
return g, x - (b // a) * y, y
def gcd(a,b):
"""totally good"""
if b==0:
return a
else:
return gcd(b,a%b)
def find_k_d_e():
global k
global d
global e
primes_list=make_pl()
for i in primes_list:
if gcd((phi),i)==1:
e=i
x,y,z=extendedEuclid(phi, e)
#x= gcd of a and b=y*a+z*b
if z>=0:
d=z
else:
d=phi+z
return
return "wrong"
def find_everything():
choose_primes_n_phi()
find_k_d_e()
find_everything()
def encrypt(m):
"""takes a number m (message) and encrypts by raising it to e and taking
it modulo n"""
c=pow(m,e,n)
return c
def decrypt(c):
"""takes and encrypted number (e) and decrypts it"""
m=pow(c,d,n)
return m
def convertToNumber (s):
"""http://stackoverflow.com
/questions/31701991/string-of-text-to-unique-integer-method Thank you poke"""
return int.from_bytes(s.encode(), 'little')
def convertFromNumber (n):
"""Thanks again poke"""
return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()
def decrypt_to_text(c):
d=decrypt(c)
t=convertFromNumber(d)
return t
def rsa():
t=input('give a string to encrypt')
m=convertToNumber(t)
c=encrypt(m)
k=int(input('enter 0 to decrypt, enter 1 to return encrypted number'))
if k==0:
print(decrypt_to_text(c))
#print(s)
elif k==1:
return c
if __name__ == '__main__':
rsa()