The encryption and decryption process described in the provided code uses RSA (Rivest-Shamir-Adleman), which is an asymmetric encryption algorithm. This means it uses two different keys: a public key for encryption and a private keyfor decryption.
Here's a breakdown of how the encryption process works :
Import Required Libraries
# Import all lib ...
import base64
import json
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
Load the public key
def load_public_key(public_key_path):
with open(public_key_path, 'rb') as pub_file:
public_key = RSA.import_key(pub_file.read())
return public_key
Load the private key
def load_private_key(private_key_path):
with open(private_key_path, 'rb') as priv_file:
private_key = RSA.import_key(priv_file.read())
return private_key
Encrypt data using the public key
def encrypt_data(data, public_key_path):
public_key = load_public_key(public_key_path)
cipher_rsa = PKCS1_OAEP.new(public_key)
encrypted_data = cipher_rsa.encrypt(data.encode())
return base64.b64encode(encrypted_data).decode('utf-8')
Decrypt data using the private key
def decrypt_data(encrypted_data, private_key_path):
encrypted_data_bytes = base64.b64decode(encrypted_data)
private_key = load_private_key(private_key_path)
cipher_rsa = PKCS1_OAEP.new(private_key)
decrypted_data = cipher_rsa.decrypt(encrypted_data_bytes)
return decrypted_data.decode()
Example usage
public_key_path = 'path_to_public_key.pem'.
private_key_path = 'path_to_private_key.pem'
# Encrypt some data
data_to_encrypt = "Hello, this is a test message!"
encrypted_data = encrypt_data(data_to_encrypt, public_key_path)
print(f"Encrypted Data: {encrypted_data}")
# Decrypt the data
decrypted_data = decrypt_data(encrypted_data, private_key_path)
print(f"Decrypted Data: {decrypted_data}")
load_public_key: Loads the RSA public key from a file.load_private_key: Loads the RSA private key from a file.encrypt_data: Encrypts the provided data using the public key.decrypt_data: Decrypts the encrypted data using the private key.