Using the RSA module of PyCryptodome one can encrypt and decrypt data easily using Python. RSA uses public-key cryptography. Using RSA one can generate a key pair consisting of a private key and a public key. The private key needs to be kept secret while the public key can be shared with others. If a sender wants to send encrypted data to a recipient, the sender needs to encrypt the data using the recipient’s public key. The recipient, in that case, can decrypt the data using her private key. And, as the private key is secret to the recipient, only the recipient can decrypt and read the data.
In this article, we would firstly generate an RSA key pair consisting of a private key and a public key. We would export both the keys to two files private_key.pem and public_key.pem. We would use a passphrase while exporting the private key so that no unauthorized party can read the private key component without the passphrase.
After that, we would encrypt a plaintext using the public key and decrypt the ciphertext using the corresponding private key.
We can generate an RSA key pair using the following code:
from Crypto.PublicKey import RSA keypair = RSA.generate(2048)
Here, we are generating 2048 bit RSA keys. The key pair has both public and private key components. We can obtain only the public key component using the following code:
from Crypto.PublicKey import RSA keypair = RSA.generate(2048) public_key = keypair.publickey()
Please note that the public key does not have any private key component. Now, we would export both the private key and the public key and write them in two files private_key.pem and public_key.pem.
from Crypto.PublicKey import RSA 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()
Please note that we are writing binary data. So, we would need to open the files in “wb” and “rb” modes for writing and reading …
0 Comments