-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay15.py
85 lines (69 loc) · 1.88 KB
/
Day15.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
import random
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
def generate_prime(bits):
while True:
num = random.getrandbits(bits)
if is_prime(num):
return num
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def multiplicative_inverse(e, phi):
d = 0
x1, x2 = 0, 1
y1, y2 = 1, 0
temp_phi = phi
while e > 0:
temp1 = temp_phi // e
temp2 = temp_phi - temp1 * e
temp_phi = e
e = temp2
x = x2 - temp1 * x1
y = y2 - temp1 * y1
x2 = x1
x1 = x
y2 = y1
y1 = y
if temp_phi == 1:
d = y2 + phi
return d % phi
def generate_keypair(bits):
p = generate_prime(bits)
q = generate_prime(bits)
n = p * q
phi = (p - 1) * (q - 1)
while True:
e = random.randrange(2, phi)
if gcd(e, phi) == 1:
break
d = multiplicative_inverse(e, phi)
return ((e, n), (d, n))
def encrypt(public_key, plaintext):
e, n = public_key
encrypted_msg = [pow(ord(char), e, n) for char in plaintext]
return encrypted_msg
def decrypt(private_key, ciphertext):
d, n = private_key
decrypted_msg = [chr(pow(char, d, n)) for char in ciphertext]
return ''.join(decrypted_msg)
#input
public_key, private_key = generate_keypair(16)
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)