data respectively.
Also, the keypair contains private key components. So, we would export the keypair using a passphrase so that no unauthorized party can read the key without having the passphrase.
Next, we would encrypt a plaintext using the public key and decrypt the ciphertext using the corresponding private key.
def encrypt(plaintext, filename): with open(filename, "rb") as file: public_key = RSA.importKey(file.read()) rsa_cipher = PKCS1_OAEP.new(public_key) ciphertext = rsa_cipher.encrypt(plaintext.encode()) return ciphertext
We are firstly importing the public key from the file public_key.pem. Next, we would initialize an RSA cipher. We are initializing the cipher with the following line of code:
rsa_cipher = PKCS1_OAEP.new(public_key)
PKCS#1 OAEP is an asymmetric cipher. It is based on RSA and the OAEP padding. As we would encrypt data using the public key, we are initializing the cipher with the public key.
Moreover, the plaintext is a string, but rsa_cipher.encrypt() method takes bytes. So, we are encoding the string to get bytes.
The decryption function is given below:
def decrypt(filename): with open(filename, "rb") as file: private_key = RSA.importKey(file.read(), 'MyPassphrase') rsa_cipher = PKCS1_OAEP.new(private_key) decrypted_text = rsa_cipher.decrypt(ciphertext) return decrypted_text
Please note that we are using the same passphrase for reading the private key from the file private_key.pem. After that, we are initializing the RSA cipher using the private key and decrypting the ciphertext using the private key.
Please note that the decrypted text is in bytes. We would need to decode() the bytes to get the plaintext string.
The complete code for encrypting and decrypting data using the RSA module of PyCryptodome is given below:
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP def encrypt(plaintext, filename): with open(filename, "rb") as file: public_key = RSA.importKey(file.read()) rsa_cipher = PKCS1_OAEP.new(public_key) ciphertext = rsa_cipher.encrypt(plaintext.encode()) return ciphertext def decrypt(filename): with open(filename, "rb") as file: private_key = RSA.importKey(file.read(), 'MyPassphrase') rsa_cipher = PKCS1_OAEP.new(private_key) decrypted_text = rsa_cipher.decrypt(ciphertext) return decrypted_text keypair = RSA.generate(2048) public_key = keypair.publickey() with open("public_key.pem", "wb") as file: file.write(public_key.exportKey('PEM')) file.close() with open("private_key.pem", "wb") as file: file.write(keypair.exportKey('PEM', 'MyPassphrase')) file.close() plaintext = "Secret Message" ciphertext = encrypt(plaintext, 'public_key.pem') print(ciphertext) decrypted_text = decrypt('private_key.pem') print(decrypted_text.decode())
I hope this helps. However, readers who want to know more about how different cryptographic algorithms work and how they are used in various secure network protocols can refer to the book “Cryptography And Public Key Infrastructure.”






0 Comments