You can download this code by clicking the button below.
This code is now available for download.
This code defines two functions, one for encrypting a message with an RSA public key, and another for decrypting a message with an RSA private key. It uses the cryptography library's hashes and asymmetric modules.
Technology Stack : cryptography library, hashes module, asymmetric module
Code Type : The type of code
Code Difficulty :
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
def encrypt_message(message, public_key):
# Encrypt a message using RSA public key
padded_message = public_key.encrypt(
message.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return padded_message
def decrypt_message(encrypted_message, private_key):
# Decrypt a message using RSA private key
decrypted_message = private_key.decrypt(
encrypted_message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return decrypted_message.decode()