Skip to content

Commit a418c20

Browse files
Initial
1 parent 02176ee commit a418c20

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

main.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from utils import *
2+
import random
3+
4+
primes = [i for i in range(100, 500) if is_prime(i)]
5+
p = random.choice(primes)
6+
q = random.choice(primes)
7+
message = input('Enter the text to be encrypted: ')
8+
9+
n = p*q
10+
k = (p-1)*(q-1)
11+
12+
for e in range(2, k):
13+
if gcd(e, k) == 1:
14+
break
15+
16+
public_key = (n, e)
17+
18+
_, b, _ = extended_gcd(e, k)
19+
if b < 0:
20+
b = b + k
21+
private_key = (n, b)
22+
23+
encrypted = encrypt(public_key, message)
24+
print(f'Encrypted message: {"".join(str(s) for s in encrypted)}')
25+
26+
decrypted = decrypt(private_key, encrypted)
27+
print(f'Decrypted message: {"".join(str(s) for s in decrypted)}')

utils.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
def is_prime(x):
2+
'''
3+
Takes an integer x and returns True if x is a prime number
4+
and Flase if x is not a prime number.
5+
'''
6+
for i in range(2, x-1):
7+
if x % i == 0:
8+
return False
9+
else:
10+
return True
11+
12+
def gcd(a, b):
13+
'''
14+
Computes the Greates Common Divisor (gcd) between integers a, b.
15+
'''
16+
if b == 0:
17+
return a
18+
else:
19+
return gcd(b, a%b)
20+
21+
def extended_gcd(x, y):
22+
'''
23+
Extended Euclidean algortihm between integers x, y to find
24+
the modular multiplicative inverse d of x under modulo y.
25+
'''
26+
if y == 0:
27+
return x, 1, 0
28+
29+
d, a, b = extended_gcd(y, x % y)
30+
31+
return d, b, a - (x // y) * b
32+
33+
def encrypt(public_key, message):
34+
'''
35+
Encryptes a string message using a public_key as a tuple of (n, e).
36+
'''
37+
encrypted = []
38+
for character in message:
39+
int_message = ord(character)
40+
n, e = public_key
41+
c = pow(int_message, e) % n
42+
encrypted.append(c)
43+
return encrypted
44+
45+
def decrypt(private_key, encrypted):
46+
'''
47+
Decryptes a string message using a private_key as a tuple of (n, d).
48+
'''
49+
decrypted = []
50+
for character in encrypted:
51+
n, d = private_key
52+
int_message = pow(character, d) % n
53+
message = chr(int_message)
54+
decrypted.append(message)
55+
return decrypted

0 commit comments

Comments
 (0)