You can download this code by clicking the button below.
This code is now available for download.
This code first generates a pair of RSA keys, then uses the public key to encrypt a message, and finally decrypts the message using the private key. It demonstrates how to handle key generation, encryption, and decryption using the cryptography library.
Technology Stack : cryptography, RSA, encryption, decryption, OAEP padding, SHA-256
Code Type : The type of code
Code Difficulty : Intermediate
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key, load_pem_private_key
import os
def generate_keys():
# Generate a private key and a public key
private_key = serialization.load_pem_private_key(
open("private_key.pem", "wb").read(),
password=None,
backend=default_backend()
)
public_key = private_key.public_key()
# Serialize the public key to PEM format
public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
backend=default_backend()
)
with open("public_key.pem", "wb") as pem_file:
pem_file.write(public_key_pem)
return private_key, public_key
def encrypt_message(message, public_key):
# Encrypt the message using the public key
encrypted = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return encrypted
def decrypt_message(encrypted_message, private_key):
# Decrypt the message using the private key
decrypted = private_key.decrypt(
encrypted_message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return decrypted
# Example usage
private_key, public_key = generate_keys()
message = b"Hello, World!"
encrypted_message = encrypt_message(message, public_key)
decrypted_message = decrypt_message(encrypted_message, private_key)
print(decrypted_message)