-
Notifications
You must be signed in to change notification settings - Fork 0
/
RSA.py
209 lines (166 loc) · 4.85 KB
/
RSA.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
from Rabin_Miller import isComposite_rabin_miller
from gcd import gcd
from fast_modular import MODULAR_EXPONENTIATION
import random
def mod_inverse(a, m):
"""
Calculate the modular multiplicative inverse of a modulo m.
Parameters:
a (int): The number whose inverse is to be calculated.
m (int): The modulus.
Returns:
int: The modular multiplicative inverse of a modulo m.
"""
m0 = m
y = 0
x = 1
if m == 1:
return 0
while a > 1:
# q is quotient
q = a // m
t = m
# m is remainder now, process same as Euclid's Algorithm
m = a % m
a = t
t = y
# Update x and y
y = x - q * y
x = t
# Make x positive
if x < 0:
x = x + m0
return x
def create_prime_nums(keylength, times=10):
"""
Create two distinct prime numbers of the given key length.
Parameters:
keylength (int): The length of the prime numbers to be generated.
Returns:
tuple: A tuple containing two distinct prime numbers.
"""
primes = set()
while len(primes) < 2:
n = random.getrandbits(keylength)
if n % 2 != 0:
prime_found = True
for _ in range(0, times):
if not isComposite_rabin_miller(n):
pass
else:
prime_found = False
break
if prime_found:
primes.add(n)
return tuple(primes)
def generate_keypair(keylength):
"""
Generate a pair of public and private keys.
Parameters:
keylength (int): The length of the key to be generated.
Returns:
tuple: A tuple containing the public and private keys: ((e, n), (d, n)).
(e, n) is the public key, and (d, n) is the private key.
"""
p, q = create_prime_nums(keylength)
n = p * q
phi = (p - 1) * (q - 1) # Euler's Totient function
# Choose an integer e such that 1 < e < phi, and e is coprime to phi.
e = random.randint(2, phi - 1)
while True:
# Check if two numbers are coprime.
if gcd(e, phi) == 1:
break
e = random.randint(1, phi)
# Use the Extended Euclidean Algorithm to generate the private key.
d = mod_inverse(e, phi)
return ((e, n), (d, n))
def mod_inverse(a, m):
"""
Calculate the modular multiplicative inverse of a modulo m.
Parameters:
a (int): The number whose inverse is to be calculated.
m (int): The modulus.
Returns:
int: The modular multiplicative inverse of a modulo m.
"""
m0 = m
y = 0
x = 1
if m == 1:
return 0
while a > 1:
# q is quotient
q = a // m
t = m
# m is remainder now, process same as Euclid's Algorithm
m = a % m
a = t
t = y
# Update x and y
y = x - q * y
x = t
# Make x positive
if x < 0:
x = x + m0
return x
def encrypt(public_key, plaintext):
"""
Encrypt a plaintext message using the public key.
Parameters:
public_key (tuple): The public key (e, n).
plaintext (int): The plaintext message to be encrypted.
Returns:
int: The encrypted ciphertext.
"""
e, n = public_key
return MODULAR_EXPONENTIATION(plaintext, e, n)
def decrypt(private_key, ciphertext):
"""
Decrypt a ciphertext message using the private key.
Parameters:
private_key (tuple): The private key (d, n).
ciphertext (int): The ciphertext message to be decrypted.
Returns:
int: The decrypted plaintext.
"""
d, n = private_key
return MODULAR_EXPONENTIATION(ciphertext, d, n)
def display():
print("_________________RSA_________________")
print("1.encrypt")
print("2.decrypt")
print("q.quit")
print("Enter the key you wanna try")
print("_____________________________________")
def main():
print("Welcome! This is a RSA encryption programme.")
keylength = int(input("Please enter the key length: \n"))
public, private = generate_keypair(keylength)
print(f"Public key: {public}")
print(f"Private key: {private}")
while True:
display()
key = input()
if key == '1':
plaintext = int(input("Please enter the plaintext message: \n"))
print("The encrypted message is:", encrypt(public, plaintext))
elif key == '2':
ciphertext = int(input("Please enter the ciphertext message: \n"))
print("The decrypted message is:", decrypt(private, ciphertext))
elif key == 'q':
break
else:
print("Invalid input! Please try again.")
if __name__ == "__main__":
main()
"""
A test sanple:
Input: 5
Output:
Welcome! This is a RSA encryption programme.
Please enter the key length:
Public key: ((5, 35), (29, 35))
Private key: ((29, 35), (5, 35))
_________________RSA_________________
"""