Comprehending the Goal
The core goal is to generate Python code for RSA encryption and decryption of textual data. I'm focusing on breaking this down into manageable steps. First, understanding the user's need; second, determining the optimal approach, including possibly starting from scratch.
Assessing Library Options
I'm now zeroing in on the libraries. PyCrypto is out; PyCryptodome seems alright but has an odd API. The cryptography library looks like the best option for industry standards and easy use. I am starting to map the necessary modules to implement the RSA functions.
Planning the Code Structure
I'm solidifying the code's structure now. Based on the outline, I need functions for key generation, encryption, and decryption. I'll include error handling and ensure the handling of bytes objects is explicit. The cryptography library's usage is relatively straightforward, so the focus will be on clarity and safety.
Refining Code Implementation
I'm now iterating on the draft code. I'm focusing on creating reusable functions for key generation, encryption, and decryption, and adding explicit handling of string-to-bytes conversions to address the user's focus on text. Additionally, I plan to include a crucial warning about the limitations of RSA's encryption length.
Developing the Functions
I'm now writing and testing the functions for key generation, encryption, and decryption, incorporating detailed comments. I'll include input validation and clear error messages. Also, I'm integrating the warning about RSA's length limitations directly into the code as a comment, and I'll include instructions on running the example.
Finalizing Code and Text
I'm now putting the finishing touches on the response. The Python script is complete, incorporating key generation, encryption, and decryption functions with robust error handling, and bytes handling. The crucial warning about RSA's length limitation is included. I'm adding instructions on how to run the example, including the pip install command. I'm also preparing to add a section about saving and loading keys in PEM format to address a frequent follow-up question.
To perform RSA encryption securely in Python, you should use the cryptography library. It is the standard, most maintained library for cryptographic recipes in Python.
Prerequisites
You will need to install the library first:
pip install cryptography
Complete Python Code
Here is a complete script that generates keys, encrypts a message, and decrypts it using modern security standards (OAEP padding).
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
def generate_keys():
"""
Generates a Private and Public Key pair.
"""
# Generate the private key
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
# Generate the public key from the private key
public_key = private_key.public_key()
return private_key, public_key
def encrypt_message(message, public_key):
"""
Encrypts a string using the Public Key.
"""
# RSA encryption usually uses OAEP padding with SHA-256
ciphertext = public_key.encrypt(
message.encode('utf-8'), # Convert string to bytes
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext
def decrypt_message(ciphertext, private_key):
"""
Decrypts the byte string using the Private Key.
"""
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext.decode('utf-8') # Convert bytes back to string
# --- Main Execution ---
if __name__ == "__main__":
# 1. Generate Keys
print("Generating keys...")
private_key, public_key = generate_keys()
# 2. Encryption
original_text = "Secret Message: Launch at dawn!"
print(f"\nOriginal Text: {original_text}")
encrypted_bytes = encrypt_message(original_text, public_key)
print(f"Encrypted (hex): {encrypted_bytes.hex()}")
# 3. Decryption
decrypted_text = decrypt_message(encrypted_bytes, private_key)
print(f"Decrypted Text: {decrypted_text}")
Explanation of the Code
- Key Generation (
generate_keys):
- We use a key size of 2048 bits. This is the current industry minimum. 4096 bits is also common.
- The
public_exponent is set to 65537 (standard default).
- Padding (OAEP):
- RSA does not encrypt raw data directly; it requires padding to be secure.
- We use OAEP (Optimal Asymmetric Encryption Padding). Older tutorials might show PKCS#1 v1.5, but that is no longer considered secure against modern attacks.
- Data Types:
- RSA works on bytes. We use
.encode('utf-8') to turn your text into bytes before encrypting, and .decode('utf-8') to turn the bytes back into text after decrypting.
Important Limitations
1. Data Size Limit:
RSA is not designed to encrypt large files or long paragraphs of text.
- With a 2048-bit key and OAEP padding, you can only encrypt about 190 bytes of data.
- If you try to encrypt a long string, the script will crash with a
ValueError: Encryption/decryption failed.
2. Solution for Large Data (Hybrid Encryption):
If you need to encrypt a large file or long text, the standard practice is:
- Generate a random symmetric key (like an AES key).
- Encrypt your large data using AES.
- Encrypt the AES key using RSA.
- Send the encrypted data + the encrypted AES key.
How to Save/Load Keys (Optional)
If you want to save these keys to files to use later:
# Save Private Key
pem_private = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption() # Use BestAvailableEncryption(b'password') for security
)
with open('private_key.pem', 'wb') as f:
f.write(pem_private)
# Save Public Key
pem_public = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_key.pem', 'wb') as f:
f.write(pem_public)