Python RSA Key pair Encryption and Decryption
Today in this article we will learn Python RSA Key pair Encryption and Decryption with examples.
We will use a Python package called PyMySQL and configure the connection parameters to include the public key for encryption and the private key for decryption.
PyMySQL supports connecting to a MySQL server using RSA keys for secure communication.
Here’s how you can use RSA keys with PyMySQL.
Generate RSA key Pair – public and private keys
First, we will generate an RSA key pair (public and private keys).
Lets the OpenSSL library generate the keys.
Open a terminal or command prompt and run the following commands.
Generate Private Keys
Let’s create a private key with a 2048-bit key length.
openssl genpkey -algorithm RSA -out privatekey.pem -pkeyopt rsa_keygen_bits:2048
Generate Public Keys
openssl rsa -pubout -in privatekey.pem -out publickey.pem
Install PyMySQL with RSA
Please install the cryptography
package,
pip install cryptography
Use RSA keys in your Python code
Kindly add below import statements
import pymysql.cursors from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization
Read RSA keys in Python code
Let’s read files from the files using the below code,
Read private keys
with open("privatekey.pem", "rb") as f: private_key = serialization.load_pem_private_key( f.read(), password=None, backend=default_backend() )
Read public keys
with open("publickey.pem", "rb") as f: public_key = serialization.load_pem_public_key( f.read(), backend=default_backend() )
Connect using RSA keys with PyMySQL
Connect to the database
connection = pymysql.connect(host='localhost', user='user', password='passwd', database='db', cursorclass=pymysql.cursors.DictCursor, "ssl": { "ca": "/path/../server-ca.pem", # Path Server CA certificate (optional) "cert": "/path/../client-cert.pem", # Path client certificate(optional) "key": "/path/../client-key.pem", # Path private key (optional) "cipher": "TLSv1.2", "keyfile": public_key, # Use public key for encryption "certfile": private_key, # Use private key for decryption })
In the above,
The ssl
property includes the paths to the server CA certificate, client certificate, and client private key.
It uses the RSA keys for encryption and decryption by setting the keyfile
and certfile
to the respective loaded keys.
Read from the database
Let’s perform read operations on the MySQL Database,
with connection.cursor() as cursor: # Read a single record sql = "SELECT `College`, `Name` FROM `Employee` WHERE `ID`=%s" cursor.execute(sql) result = cursor.fetchone() print(result)
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.