4.1 SIMPLE RSA ENCRYPTION
EXERCISE 4.1: SIMPLE RSA ENCRYPTION
Using the preceding application, set up communication from Alice to Bob and then send a few encrypted messages from Alice to Bob for decryption.
Here is a 2 minute youtube video explaining it all.
In the video, you will see that Alice generates her private and public key pair. Bob then uses Alice’s public key and sends her encrypted messages. Alice will then decrypt the messages she received from Bob by using her private key.
# listing4_4.py
import gmpy2,os, binascii
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
#### DANGER ####
# THE FOLLOWING RSA ENCRYPTION AND DECRYPTION IS COMPLETELY UNSAFE AND
# TERRIBLY BROKEN. DO NOT USE FOR ANYTHING OTHER THAN THE PRACTICE
# EXERCISE
################
def simple_rsa_encrypt(m, public_key):
= public_key.public_numbers()
numbers return gmpy2.powmod(m, numbers.e, numbers.n)
def simple_rsa_decrypt(c, private_key):
= private_key.private_numbers()
numbers return gmpy2.powmod(c, numbers.d, numbers.public_numbers.n)
def int_to_bytes(i):
# i might be a gmpy2 big integer; convert back to a Python int.
= int(i)
i return i.to_bytes((i.bit_length()+7)//8, byteorder='big')
def bytes_to_int(b):
return int.from_bytes(b, byteorder='big')
def main():
= None
public_key_file = None
private_key_file = None
public_key = None
private_key
while True:
print("Simple RSA Crypto")
print("------------------")
print("\tprivate key file: {}".format(private_key_file))
print("\tpublic_key_file: {}".format(public_key_file))
print("\t1. Encrypt Message")
print("\t2. Decrypt Message.")
print("\t3. Load public key file ")
print("\t4. Load private key file.")
print("\t5. Create and load new public and private key files.")
print("\t6. Quit.\n")
= input(">> ")
choice
if choice == "1":
if not public_key:
print("\nNo public key loaded\n")
else:
= input("\nPlaintext: ").encode()
message = bytes_to_int(message)
message_as_int = simple_rsa_encrypt(message_as_int, public_key)
cipher_as_int = int_to_bytes(cipher_as_int)
cipher print("\nCiphertext (hexlified): {}\n".format(binascii.hexlify(cipher)))
elif choice == '2':
if not private_key:
print("\nNo private key loaded\n")
else:
= input("\nCiphertext (hexlified): ").encode()
cipher_hex = binascii.unhexlify(cipher_hex)
cipher = bytes_to_int(cipher)
cipher_as_int = simple_rsa_decrypt(cipher_as_int, private_key)
message_as_int = int_to_bytes(message_as_int)
message print("\nPlaintext: {}\n".format(message))
elif choice == '3':
= input("\nEnter public key file: ")
public_key_temp_file if not os.path.exists(public_key_temp_file):
print(f"File {public_key_temp_file} does not exist.")
continue
with open(public_key_temp_file, 'rb') as f:
= serialization.load_pem_public_key(
public_key =f.read(),
data=default_backend()
backend
)= public_key_temp_file
public_key_file print("\nPublic Key file loaded.\n")
# unload private key if any
= None
private_key_file = None
private_key elif choice == '4':
= input("\nEnter private key file: ")
private_key_file_temp if not os.path.exists(private_key_file_temp):
print(f"File {private_key_file_temp} does not exist.")
continue
with open(private_key_file_temp, 'rb') as f:
= serialization.load_pem_private_key(
private_key =f.read(),
data=default_backend(),
backend=None
password
) = private_key_file_temp
private_key_file print("\nPrivate Key file loaded.\n")
# load public key for the given private key
# (unload previous public key if any)
= private_key.public_key()
public_key = None
public_key_file elif choice == '5':
= input("\nEnter a file name for new private key: ")
private_key_file_temp = input("\nEnter a file name for a new public key: ")
public_key_file_temp
if os.path.exists(private_key_file_temp) or os.path.exists(public_key_file_temp):
print("File already exists")
continue
with open(private_key_file_temp, "wb+") as private_key_file_obj:
with open(public_key_file_temp, "wb+") as public_key_file_obj:
= rsa.generate_private_key(
private_key =65537,
public_exponent=2048,
key_size=default_backend(),
backend
)= private_key.public_key()
public_key
private_key_file_obj.write(
private_key.private_bytes(=serialization.Encoding.PEM,
encodingformat=serialization.PrivateFormat.TraditionalOpenSSL,
=serialization.NoEncryption(),
encryption_algorithm
)
)
public_key_file_obj.write(
public_key.public_bytes(=serialization.Encoding.PEM,
encodingformat=serialization.PublicFormat.SubjectPublicKeyInfo,
)
)
= None
public_key_file = private_key_file_temp
private_key_file elif choice == '6':
print("\n\nTerminating. This program will self destruct in 5 seconds. \n")
break
else:
print("\n\nUnknown Option {}.\n".format(choice))
if __name__ == '__main__':
main()