-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTEST.py
More file actions
74 lines (61 loc) · 1.75 KB
/
Copy pathTEST.py
File metadata and controls
74 lines (61 loc) · 1.75 KB
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
import random
import math
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif number % 2 == 0 or number % 3 == 0:
return False
i = 5
while i * i <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
return True
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def mod_inverse(a, m):
m0, x0, x1 = m, 0, 1
while a > 1:
q = a // m
m, a = a % m, m
x0, x1 = x1 - q * x0, x0
return x1 + m0 if x1 < 0 else x1
def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError("Both numbers must be prime.")
elif p == q:
raise ValueError("p and q cannot be equal.")
n = p * q
phi = (p - 1) * (q - 1)
e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
d = mod_inverse(e, phi)
return ((e, n), (d, n))
def encrypt(public_key, plaintext):
e, n = public_key
cipher = [pow(ord(char), e, n) for char in plaintext]
return cipher
def decrypt(private_key, ciphertext):
d, n = private_key
plain = [chr(pow(char, d, n)) for char in ciphertext]
return ''.join(plain)
if __name__ == "__main__":
# Example usage
p = 7
q = 19
public_key, private_key = generate_keypair(p, q)
print("Public Key:", public_key)
print("Private Key:", private_key)
message = "Hello, RSA!"
print("Original Message:", message)
encrypted_message = encrypt(public_key, message)
print("Encrypted Message:", encrypted_message)
decrypted_message = decrypt(private_key, encrypted_message)
print("Decrypted Message:", decrypted_message)