The user wants a Python tool to encrypt messages with RSA.
I need to provide a complete, working example.
RSA encryption involves key generation (public and private), encryption using the public key, and decryption using the private key (to verify it works, or just the encryption part if specifically asked, but usually "encrypt" implies the whole mechanism).
I should use the cryptography library as it is the standard, secure, and easy-to-use library for Python. The rsa library is also an option, but cryptography is generally preferred for production-level code.
Steps to create the tool:
-
Install dependencies: The user needs cryptography.
-
Key Generation: Need a function to generate a private key and derive the public key from it. These should probably be saved to files (e.g., private_key.pem, public_key.pem) so they persist.
-
Encryption: Need a function that takes a message and a public key, encrypts the message.
- Crucial detail: RSA on its own is deterministic and slow. You don't encrypt large messages directly with RSA. You use hybrid encryption (generate a random session key for AES, encrypt the message with AES, encrypt the session key with RSA).
- However, for a "simple tool", doing direct RSA with padding (OAEP) is often what beginners expect, but it has a size limit (key size - padding overhead).
- The
cryptography library handles the padding (OAEP).
- To keep it simple but correct: I will implement OAEP padding.
- If the user wants to encrypt large messages, the code gets complex (hybrid). I will stick to standard RSA-OAEP for smaller messages and add a note about file sizes, or perhaps just show the hybrid approach if I want to be robust.
- Decision: Let's stick to standard RSA-OAEP. It's the standard "textbook" implementation in Python using
cryptography. If the message is too big, the library will throw an error, which I can handle or explain.
-
Decryption: Even though the prompt asks to "encrypt", an encryption tool is useless if you can't decrypt to check it. I'll include a decryption function.
-
Code Structure:
- Import
cryptography.hazmat...
- Function
generate_keys()
- Function
encrypt_message(message, public_key_path)
- Function
decrypt_message(encrypted_message, private_key_path)
main block to run it.
Refining the Code:
- Padding: Must use OAEP (Optimal Asymmetric Encryption Padding) with SHA256. MGF1 (Mask Generation Function) also with SHA256.
- Serialization: Keys should be PEM format.
- Encoding: Strings need to be encoded to bytes before encryption, and base64 encoded after encryption (to make the ciphertext copy-pasteable).
Drafting the explanation:
- Prerequisites:
pip install cryptography.
- The Code: A single script or separate functions. I'll provide a complete script.
- How it works: Explain Key Gen, Public Key encryption, Private Key decryption.
Self-Correction/Edge Case Check:
- What if the message is too long? RSA with 2048-bit keys can only encrypt a very small amount of data (around 200 bytes).
- Should I implement Hybrid encryption? It makes the code much longer (AES + RSA).
- Compromise: I will implement standard RSA-OAEP. I will add a comment/warning that RSA is for small data (like keys or short strings), not huge files. For huge files, they need hybrid encryption. This keeps the code simple and understandable for the user's specific request "encrypt messages".
Final Plan:
- Show how to install the library.
- Provide a Python script that:
- Generates keys if they don't exist.
- Encrypts a string using the public key.
- Decrypts the string using the private key (to demonstrate proof of concept).
- Explain the code blocks.
Let's write the code mentally:
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.backends import default_backend
# Gen keys
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
public_key = private_key.public_key()
# Save keys (PEM)
pem_private = private_key.private_bytes(...)
pem_public = public_key.public_bytes(...)
# Encrypt
ciphertext = public_key.encrypt(
message,
padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
)
This looks solid. I will wrap this in a nice class or set of functions.
One specific formatting thing: The output of encryption is bytes. It's best to Base64 encode it so the user can actually see/read/copy the encrypted message string. I will include base64.
Structure of the response:
- Introduction.
- Installation command.
- The Python Code (commented).
- Explanation of the steps.
- Important Security Note (Size limits).
Let's go.
Here is a complete, step-by-step guide and a Python script to encrypt and decrypt messages using RSA.
Prerequisites
We will use the cryptography library, which is the standard for cryptographic operations in Python.
- Install the library:
pip install cryptography
The Python Tool
This script generates keys, encrypts a message using a Public Key, and decrypts it using a Private Key.
I have included Base64 encoding in the output. Since RSA encryption produces raw bytes (which look like gibberish or cause encoding errors if printed directly), Base64 converts them into a readable string format that is safe to copy-paste.
import base64
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.backends import default_backend
class RSATool:
def __init__(self):
# Default key size
self.key_size = 2048
def generate_keys(self):
"""Generates a new Private/Public key pair."""
print("Generating RSA keys (2048-bit)...")
# Generate Private Key
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=self.key_size,
backend=default_backend()
)
# Derive Public Key from Private Key
self.public_key = self.private_key.public_key()
print("Keys generated successfully.\n")
def save_keys_to_files(self, private_filename="private_key.pem", public_filename="public_key.pem"):
"""Saves keys to .pem files for later use."""
# Save Private Key
with open(private_filename, "wb") as f:
f.write(self.private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
# Save Public Key
with open(public_filename, "wb") as f:
f.write(self.public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
))
print(f"Keys saved to '{private_filename}' and '{public_filename}'.")
def load_keys_from_files(self, private_filename="private_key.pem", public_filename="public_key.pem"):
"""Loads keys from .pem files."""
try:
with open(private_filename, "rb") as f:
self.private_key = serialization.load_pem_private_key(
f.read(),
password=None,
backend=default_backend()
)
with open(public_filename, "rb") as f:
self.public_key = serialization.load_pem_public_key(
f.read(),
backend=default_backend()
)
print("Keys loaded successfully.")
return True
except FileNotFoundError:
print("Error: Key files not found. Please generate keys first.")
return False
def encrypt_message(self, message):
"""
Encrypts a string message using the Public Key.
Returns a Base64 encoded string (safe for text transmission).
"""
if not hasattr(self, 'public_key'):
raise ValueError("Public Key not loaded or generated.")
# Convert string to bytes
message_bytes = message.encode('utf-8')
# Encrypt using OAEP padding (Standard for RSA)
ciphertext_bytes = self.public_key.encrypt(
message_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Return as readable Base64 string
return base64.b64encode(ciphertext_bytes).decode('utf-8')
def decrypt_message(self, encrypted_message_b64):
"""
Decrypts a Base64 encoded string using the Private Key.
Returns the original string.
"""
if not hasattr(self, 'private_key'):
raise ValueError("Private Key not loaded or generated.")
# Decode Base64 back to raw bytes
ciphertext_bytes = base64.b64decode(encrypted_message_b64)
# Decrypt using OAEP padding
decrypted_bytes = self.private_key.decrypt(
ciphertext_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return decrypted_bytes.decode('utf-8')
# --- Usage Example ---
if __name__ == "__main__":
rsa_tool = RSATool()
# 1. Generate Keys (Run this once)
rsa_tool.generate_keys()
rsa_tool.save_keys_to_files()
# 2. Define a secret message
original_message = "This is a top secret password: 12345!"
print(f"Original: {original_message}")
# 3. Encrypt (This only requires the Public Key)
encrypted_str = rsa_tool.encrypt_message(original_message)
print(f"\nEncrypted (Base64): {encrypted_str}")
# 4. Decrypt (This requires the Private Key)
try:
decrypted_str = rsa_tool.decrypt_message(encrypted_str)
print(f"\nDecrypted: {decrypted_str}")
except Exception as e:
print(f"Decryption failed: {e}")
How it works
-
Key Generation (rsa.generate_private_key):
RSA relies on a pair of mathematically linked keys.
- Public Key: Can be shared with anyone. Used to encrypt data.
- Private Key: Must be kept secret. Used to decrypt data.
- We use a key size of 2048 bits, which is the current industry standard for security.
-
Padding (padding.OAEP):
You cannot simply msg^e mod n (textbook RSA) because it is insecure and deterministic (encrypting "hello" twice results in the same output).
We use OAEP (Optimal Asymmetric Encryption Padding) with SHA-256. This adds random data to the message so that the ciphertext is different every time you encrypt the same message.
-
Base64 Encoding:
RSA produces raw bytes. If you try to print() raw bytes in a terminal, you might see symbols that crash your terminal or are impossible to copy.
base64 converts those bytes into standard ASCII characters (A-Z, a-z, 0-9, +, /), making the encrypted message easy to send via email, chat, or JSON.
Important Limitation
RSA has a data size limit.
With a 2048-bit key and OAEP padding, you can only encrypt messages up to roughly 190 bytes (characters).
- If you need to encrypt a large file (like an image or a long document): Do not encrypt the file directly with RSA.
- The Solution (Hybrid Encryption):
- Generate a random AES Symmetric Key (e.g., a 32-byte password).
- Encrypt your large file with that AES key (fast, unlimited size).
- Encrypt the small AES key using your RSA Public Key.
- Send the encrypted file + the encrypted AES key.