I'm currently focused on the essential components of RSA. I've begun to break down the user's need for an encryption tool, specifically the RSA implementation. Right now, I'm defining the prerequisites: this tool must be built on the RSA algorithm, which is asymmetric.
Mapping the Implementation Path
I'm now charting the steps required to build the tool. The core is the cryptography library. Step one will cover the setup and library installation. After that, I'll provide detailed RSA key generation, encryption, and decryption functions using the chosen library and explain the security best practices, like padding and hashing, to ensure secure implementation.
Analyzing Implementation Steps
I've been meticulously refining the steps of the implementation. I've chosen cryptography over alternatives. Now, I'm defining each step in detail: installation, key generation (including saving keys), encryption (OAEP padding with SHA-256), decryption, and overall structure. I am leaning towards creating an RSAKeyManager class.
Constructing the Code Blocks
I'm now in the process of formulating code blocks based on the outlined implementation plan. I'm focusing on key generation (private and public), and implementing encryption and decryption. I'll need to remember to convert inputs to bytes and handle the output for ease of use. I'm leaning heavily on PEM file handling and Base64 encoding for readability. I'll need to integrate those steps, as well.
Formulating the Class Structure
I'm now sketching out the RSACipher class and its methods. I've decided to prioritize a streamlined approach, focusing on the core encryption and decryption functions within the class. While I'll include key generation and basic file I/O within the class itself, for now, I'll streamline key saving to the usage example, and provide simple usage examples. I'm focusing on simplicity, so I can include this in a single code block. I am making sure to add helpful comments.
To build a secure RSA encryption tool in Python, it is highly recommended to use the established cryptography library. It provides robust security primitives, including proper padding (OAEP) which is crucial for RSA security.
DO NOT write your own math for RSA implementation; it will likely be insecure.
Step 1: Install Prerequisites
You will need to install the cryptography package via your terminal:
bash
pip install cryptography
Step 2: The Python Tool
Here is a complete, object-oriented script. It handles key generation, loading/saving keys to files, and encrypting/decrypting messages using Base64 encoding (to make the encrypted output readable).
python
Key Concepts Explained
Asymmetric Encryption: RSA uses two keys.
Public Key: Shared with anyone. Used to Encrypt the message.
Private Key: Kept secret. Used to Decrypt the message.
OAEP Padding: In the code, you see padding.OAEP. Raw RSA is deterministic (encrypting "hello" twice produces the same result) and vulnerable to mathematical attacks. OAEP adds randomness to the process, ensuring the same message looks different every time it is encrypted.
Base64: RSA encryption produces raw binary data (bytes) which looks like garbage characters when printed. We wrap it in Base64 effectively to turn it into a safe string format for copying, pasting, or sending over HTTP.
Important Limitation: Message Size
RSA is very slow and cannot encrypt large amounts of data.
With a 2048-bit key, the maximum message size is roughly 190 bytes.
It is primarily used to encrypt symmetric keys (like an AES password), not the file/message itself.
For large messages/files:
You should use Hybrid Encryption:
Generate a random AES key.
Encrypt your large message with AES (fast).
Encrypt the AES key with RSA (secure).
Send the encrypted AES key and the encrypted message together.
import base64
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
class RSACipher:
def __init__(self):
self.private_key = None
self.public_key = None
def generate_keys(self, key_size=2048):
"""Generates a Public/Private key pair."""
print(f"Generating {key_size}-bit RSA keys...")
self.private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
)
self.public_key = self.private_key.public_key()
def encrypt(self, message, public_key=None):
"""
Encrypts a string message.
Returns: Base64 encoded string of the encrypted binary data.
"""
if not public_key:
public_key = self.public_key
if not public_key:
raise ValueError("Public key not found. Generate or load keys first.")
# Convert string to bytes
message_bytes = message.encode('utf-8')
# Encrypt using OAEP padding (Standard secure padding)
ciphertext = public_key.encrypt(
message_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Return base64 string so it helps with display/storage
return base64.b64encode(ciphertext).decode('utf-8')
def decrypt(self, b64_ciphertext):
"""
Decrypts a Base64 encoded string.
Returns: Decrypted string message.
"""
if not self.private_key:
raise ValueError("Private key not found. Generate or load keys first.")
try:
# Decode Base64 back to raw bytes
ciphertext = base64.b64decode(b64_ciphertext)
plaintext = self.private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext.decode('utf-8')
except Exception as e:
return f"Decryption failed: {str(e)}"
def save_keys_to_file(self, private_filename="private.pem", public_filename="public.pem"):
"""Saves keys to PEM files."""
if self.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() # Use BestAvailableEncryption(b'pass') for password protection
))
if self.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_file(self, private_filename="private.pem", public_filename="public.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 # Add password here if the key was encrypted
)
with open(public_filename, "rb") as f:
self.public_key = serialization.load_pem_public_key(f.read())
print("Keys loaded successfully.")
except FileNotFoundError:
print("Key files not found.")
# --- Usage Example ---
if __name__ == "__main__":
tool = RSACipher()
# 1. Generate Keys
tool.generate_keys()
# 2. Message to encrypt
my_secret = "This is a top secret message for your eyes only."
print(f"\nOriginal Message: {my_secret}")
# 3. Encrypt
encrypted_msg = tool.encrypt(my_secret)
print(f"Encrypted (Base64): {encrypted_msg}")
# 4. Decrypt
decrypted_msg = tool.decrypt(encrypted_msg)
print(f"Decrypted Message: {decrypted_msg}")
# 5. Save keys for later use
# tool.save_keys_to_file()