Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import random

import math

def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True

def generate_prime(bits):
while True:
num = random.getrandbits(bits)
if is_prime(num):
return num

def gcd(a, b):


while b:
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(bit_length):
p = generate_prime(bit_length)
q = generate_prime(bit_length)
n = p * q
phi = (p - 1) * (q - 1)

e = random.randint(2, phi - 1)
while gcd(e, phi) != 1:
e = random.randint(2, phi - 1)

d = mod_inverse(e, phi)

return ((e, n), (d, n))

def encrypt(msg_plaintext, public_key):


e, n = public_key
msg_ciphertext = [pow(ord(c), e, n) for c in msg_plaintext]
return msg_ciphertext

def decrypt(msg_ciphertext, private_key):


d, n = private_key
msg_plaintext = [chr(pow(c, d, n)) for c in msg_ciphertext]
return ''.join(msg_plaintext)

if __name__ == "__main__":
bit_length = 16

public, private = generate_keypair(bit_length)


print("Public Key (e, n):", public)
print("Private Key (d, n):", private)

msg = input("Enter a message to be encrypted: ")

encrypted_msg = encrypt(msg, public)


print("Encrypted Message:", encrypted_msg)

decrypted_msg = decrypt(encrypted_msg, private)


print("Decrypted Message:", decrypted_msg)

You might also like