The user wants Python code to encrypt and decrypt text using RSA.
Identify the library: The standard and most robust library for cryptographic operations in Python is cryptography. Specifically, the cryptography.hazmat.primitives.asymmetric module handles RSA. Another popular, though sometimes less current-in-style, library is PyCryptodome (which is a fork of the old PyCrypto). I should probably provide a solution using cryptography as it's the modern standard, but maybe mention PyCryptodome as an alternative if they want something simpler/older-style. For this primary response, I will stick to cryptography because it's best practice.
Core Steps for RSA:
Key Generation: Need to generate a public/private key pair.
Serialization: Saving keys to PEM format (standard text format) is usually helpful so they can be reused.
Encryption: Use the Public Key.
Decryption: Use the Private Key.
Padding: RSA must be used with padding (like OAEP) to be secure. I must emphasize this.
Handling "Text" vs "Bytes": Encryption works on bytes, not strings. I need to encode text to bytes (UTF-8) before encryption and decode back to text after decryption.
Drafting the Code Structure (Mental or Scratchpad):
Imports: from cryptography.hazmat.primitives.asymmetric import rsa, padding, from cryptography.hazmat.primitives import serialization, hashes.
Refining the Code Example:
It's best to create a clean class or a set of functions.
Let's create a script that:
Generates keys.
Encrypts a string.
Decrypts the result.
Prints outputs.
Constraint Check: RSA has a limit on message size (key size - padding overhead). For a general example, a short message is fine. If the user asks for large file encryption, I should mention Hybrid Encryption (AES + RSA), but for "text", simple RSA is what they usually expect first.
Adding Explanations:
Explain what cryptography is.
Explain Padding (OAEP) - crucial for security.
Explain Key Size (2048 bits is standard).
Explain that you encrypt with Public and decrypt with Private.
Alternative Library (PyCryptodome):
Some users find cryptography (the lib) a bit verbose. PyCryptodome is often seen in tutorials.
Code snippet idea: from Crypto.PublicKey import RSA, from Crypto.Cipher import PKCS1_OAEP.
I will stick to the cryptography library as the primary answer because it is actively maintained and considered the standard for production code.
Padding: Use padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None). This is the standard secure padding.
Serialization: Show how to save/load keys as PEM strings or files, as that's a common requirement.
Self-Correction during drafting:
Issue: RSA can only encrypt data smaller than the modulus.
Resolution: Add a warning comment or note that RSA is for small data (like keys or short strings), not large files.
Constructing the final response:
Prerequisite (pip install cryptography).
The complete, runnable script.
Explanation of the components.
Note on Hybrid Encryption (optional but good practice to mention).
Let's write the code.
Here is a complete Python script to handle RSA encryption and decryption.
I recommend using the cryptography library, as it is the modern standard for cryptographic operations in Python (replacing the older, deprecated PyCrypto).
Prerequisite
You will need to install the library first:
bash
pip install cryptography
Python Code
This script generates keys, encrypts a string, and then decrypts it. It uses OAEP (Optimal Asymmetric Encryption Padding), which is the recommended standard for secure RSA encryption.
python
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.backends import default_backend
import base64
def generate_keys():
"""
Generates a new RSA private/public key pair.
"""
# Generate private key (2048 bits is standard)
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
# Derive public key from private key
public_key = private_key.public_key()
return private_key, public_key
def encrypt_message(message, public_key):
"""
Encrypts a string message using the public key.
Returns a Base64 encoded string for easy readability/transmission.
"""
# Convert string to bytes
message_bytes = message.encode('utf-8')
# Encrypt using OAEP padding (Standard and secure)
ciphertext = public_key.encrypt(
message_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Return as Base64 string so it's printable
return base64.b64encode(ciphertext).decode('utf-8')
def decrypt_message(encrypted_b64, private_key):
"""
Decrypts a Base64 encoded ciphertext using the private key.
"""
# Decode Base64 back to raw bytes
ciphertext = base64.b64decode(encrypted_b64)
# Decrypt using the same OAEP padding
plaintext_bytes = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Convert bytes back to string
return plaintext_bytes.decode('utf-8')
# --- Example Usage ---
if __name__ == "__main__":
# 1. Generate Keys
private_key, public_key = generate_keys()
print("Keys generated.")
# 2. Define the message
original_message = "This is a secret message for RSA!"
print(f"Original: {original_message}")
# 3. Encrypt
encrypted_msg = encrypt_message(original_message, public_key)
print(f"Encrypted: {encrypted_msg}")
# 4. Decrypt
decrypted_msg = decrypt_message(encrypted_msg, private_key)
print(f"Decrypted: {decrypted_msg}")
How it works:
Key Generation: We create a 2048-bit key pair. The Private Key is kept secret (used to decrypt), and the Public Key is shared (used to encrypt).
Padding (OAEP): RSA requires "padding" to be secure. We use OAEP with SHA-256 hashing. If you try to decrypt with a different padding scheme than the one used to encrypt, it will fail.
Base64 Encoding: RSA produces raw bytes that often look like gibberish or unprintable characters. The script encodes these bytes into a Base64 string to make the encrypted result readable and easy to copy-paste.
Limits: RSA can only encrypt data smaller than the key size (roughly 190 bytes for a 2048-bit key with OAEP). If you need to encrypt large files or long text, you should use Hybrid Encryption (generate a random AES key, encrypt the data with AES, and encrypt the AES key with RSA).