Skip to content

Commit 3380f2a

Browse files
authored
Add files via upload
1 parent 4a6c115 commit 3380f2a

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Day15.py

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import random
2+
3+
def is_prime(n):
4+
if n <= 1:
5+
return False
6+
elif n <= 3:
7+
return True
8+
elif n % 2 == 0 or n % 3 == 0:
9+
return False
10+
i = 5
11+
while i * i <= n:
12+
if n % i == 0 or n % (i + 2) == 0:
13+
return False
14+
i += 6
15+
return True
16+
17+
def generate_prime(bits):
18+
while True:
19+
num = random.getrandbits(bits)
20+
if is_prime(num):
21+
return num
22+
23+
def gcd(a, b):
24+
while b != 0:
25+
a, b = b, a % b
26+
return a
27+
28+
def multiplicative_inverse(e, phi):
29+
d = 0
30+
x1, x2 = 0, 1
31+
y1, y2 = 1, 0
32+
temp_phi = phi
33+
34+
while e > 0:
35+
temp1 = temp_phi // e
36+
temp2 = temp_phi - temp1 * e
37+
temp_phi = e
38+
e = temp2
39+
40+
x = x2 - temp1 * x1
41+
y = y2 - temp1 * y1
42+
43+
x2 = x1
44+
x1 = x
45+
y2 = y1
46+
y1 = y
47+
48+
if temp_phi == 1:
49+
d = y2 + phi
50+
51+
return d % phi
52+
53+
def generate_keypair(bits):
54+
p = generate_prime(bits)
55+
q = generate_prime(bits)
56+
n = p * q
57+
phi = (p - 1) * (q - 1)
58+
59+
while True:
60+
e = random.randrange(2, phi)
61+
if gcd(e, phi) == 1:
62+
break
63+
64+
d = multiplicative_inverse(e, phi)
65+
return ((e, n), (d, n))
66+
67+
def encrypt(public_key, plaintext):
68+
e, n = public_key
69+
encrypted_msg = [pow(ord(char), e, n) for char in plaintext]
70+
return encrypted_msg
71+
72+
def decrypt(private_key, ciphertext):
73+
d, n = private_key
74+
decrypted_msg = [chr(pow(char, d, n)) for char in ciphertext]
75+
return ''.join(decrypted_msg)
76+
77+
#input
78+
public_key, private_key = generate_keypair(16)
79+
message = "Hello, RSA!"
80+
print("Original message:", message)
81+
encrypted_message = encrypt(public_key, message)
82+
print("Encrypted message:", encrypted_message)
83+
decrypted_message = decrypt(private_key, encrypted_message)
84+
print("Decrypted message:", decrypted_message)
85+

0 commit comments

Comments
 (0)