Writing RSA encryption code
The user wants Python code to encrypt and decrypt text using RSA encryption. I need to demonstrate key generation, encryption, and decryption, focusing on best practices. Using a library like cryptography or PyCryptodome is essential, avoiding hand-rolled RSA. Since the request is generic, I'll lean towards the cryptography library due to its modern usage. I’ll include necessary padding and serialization while keeping the code concise, ensuring it covers key generation, encryption, and decryption clearly.Crafting Python RSA script
I’m thinking about creating a single script with comments that demonstrates secure RSA encryption and decryption practices. I need to ensure it uses OAEP with MGF1(SHA256) for padding and shows how to encode text to bytes using UTF-8. The user didn't ask for library installation details, but I could mention needing to run pip install cryptography. I’ll focus on using the cryptography library for this example since it’s widely recommended, while also considering a minimal code approach.Reviewing RSA code example
I'm creating possible Python code for RSA encryption and decryption using the cryptography library. The code includes generating keys, encrypting plaintext, and decrypting ciphertext, all with OAEP padding. It also considers UTF-8 encoding for text.
I could show serialization for the private key, but it might be extra information. Since the user hasn't requested saving or loading keys, I think I'll keep the focus on key generation, encryption, and decryption, while mentioning the need to install cryptography via pip.Crafting final response
I want to create a final answer that includes a text explanation alongside the complete script for RSA encryption and decryption. I'll ensure the explanation is clear and straightforward, making it easy for the user to understand. I need to focus on providing valuable insights without mentioning anything about knowledge cutoffs. So, let's get that ready to deliver a complete and helpful answer! Here’s a simple, secure example using the cryptography library with RSA and OAEP padding (recommended for real use).
First, install the dependency:
pip install cryptography
Full Example: Generate Keys, Encrypt, Decrypt
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
# ---------- Key generation ----------
def generate_rsa_key_pair(key_size: int = 2048):
"""
Generate an RSA private/public key pair.
"""
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
)
public_key = private_key.public_key()
return private_key, public_key
# ---------- Encryption / Decryption ----------
def rsa_encrypt(plaintext: str, public_key) -> bytes:
"""
Encrypt a UTF-8 string using an RSA public key.
Returns ciphertext bytes.
"""
ciphertext = public_key.encrypt(
plaintext.encode("utf-8"),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
return ciphertext
def rsa_decrypt(ciphertext: bytes, private_key) -> str:
"""
Decrypt ciphertext bytes using an RSA private key.
Returns a UTF-8 string.
"""
decrypted_bytes = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
),
)
return decrypted_bytes.decode("utf-8")
# ---------- Demo usage ----------
if __name__ == "__main__":
# 1. Generate keys
private_key, public_key = generate_rsa_key_pair()
# 2. Encrypt a message
message = "Hello, RSA encryption!"
ciphertext = rsa_encrypt(message, public_key)
print("Ciphertext (bytes):", ciphertext)
# 3. Decrypt the message
decrypted = rsa_decrypt(ciphertext, private_key)
print("Decrypted text:", decrypted)
If you also want code to save/load the keys (PEM format), I can add that as well.