Implementing RSA in Python
The user wants Python code for RSA encryption and decryption without using external libraries. I'll make sure to generate keys, encrypt, and decrypt by including essential functions like is_prime, gcd, modinv, and powmod. For key generation, I'll pick two small primes (noting that this is insecure), compute n and phi, and choose an e such that it is coprime to phi. During encryption, I'll convert the message to an integer and ensure it's smaller than n. Decryption involves reversing this process, using built-in Python tools.Creating a Full RSA Example
I want to provide a complete RSA example in a single script and demonstrate the functionality without getting overly detailed. I'll include comments for clarity while also cautioning about security, emphasizing that this is just for demonstration purposes. Using larger primes for a real application is crucial. For generating primes, I could implement the Miller-Rabin primality test, while keeping it simple. I plan to use secrets for generating 16-bit primes by default, but they'll have the flexibility to adjust this. I'll keep the bit size small for quicker computations while following standard libraries.Implementing Miller-Rabin Primality Test
I'm focusing on the Miller-Rabin primality test, specifically with the is_probable_prime(n, k=20) function. It’ll help in determining if a number is prime. The generate_prime(bits) function will also ensure the most significant and least significant bits are set correctly. Although the user didn't specifically ask about prime generation details, they likely want a fully functional example, so I think it's important to include that as well. I'll aim for clarity in the code.Crafting the RSA Script
I'm creating a Python script for RSA encryption and decryption. I’ll start by importing secrets and defining essential functions like egcd, modinv, and is_probable_prime. The generate_prime(bits) function will generate a random prime number with the specified bits, ensuring it's appropriately formed. For key generation, I'll create generate_keys(bits=512), which generates two distinct primes, computes n, and derives e and d.
Next, I'll implement the encrypt and decrypt functions to handle messages. The encryption will convert the message to an integer and raise an error if the message is too long for the key size. Decryption will involve reverting the cipher back to bytes and decoding it. Finally, I’ll consider outputting ciphertext as a hex string as well.Building the RSA Response
I'm considering showing the base64 representation of the ciphertext, but the user might prefer working with integers. Since the requirement is to avoid external libraries, I need to clarify that using standard libraries is permissible. It's important to mention that proper RSA implementations utilize padding like OAEP for security, while our version is naive and less secure. Also, Python's pow function can handle modular exponentiation without any issues. I’ll keep the explanations concise as I craft the final response. Below is a self‑contained example of RSA key generation, encryption, and decryption in Python using only the standard library (no third‑party libraries).
Note: This is a minimal educational implementation. It does not include proper padding (e.g., OAEP), so it is not secure for real‑world use.
import secrets
import math
# ---------------------------------------
# Basic number theory helpers
# ---------------------------------------
def gcd(a, b):
while b:
a, b = b, a % b
return a
def extended_gcd(a, b):
"""Return (g, x, y) such that a*x + b*y = g = gcd(a, b)."""
if b == 0:
return a, 1, 0
g, x1, y1 = extended_gcd(b, a % b)
return g, y1, x1 - (a // b) * y1
def modinv(a, m):
"""Modular inverse of a modulo m, i.e. a * x ≡ 1 (mod m)."""
g, x, _ = extended_gcd(a, m)
if g != 1:
raise ValueError("No modular inverse")
return x % m
# ---------------------------------------
# Primality test and prime generation
# ---------------------------------------
def is_probable_prime(n, k=20):
"""Miller-Rabin primality test."""
if n < 2:
return False
# small primes quick check
small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
if n in small_primes:
return True
if any(n % p == 0 for p in small_primes):
return False
# write n - 1 as 2^r * d with d odd
r, d = 0, n - 1
while d % 2 == 0:
r += 1
d //= 2
for _ in range(k):
a = secrets.randbelow(n - 3) + 2 # in [2, n-2]
x = pow(a, d, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
def generate_prime(bits):
"""Generate a random probable prime with the given bit length."""
while True:
# ensure the top bit and low bit are set (odd, correct size)
p = secrets.randbits(bits)
p |= (1 << (bits - 1)) | 1
if is_probable_prime(p):
return p
# ---------------------------------------
# RSA key generation
# ---------------------------------------
def generate_rsa_keys(bits=512):
"""Generate RSA public and private keys."""
# 1. Choose two distinct large primes p and q
p = generate_prime(bits)
q = generate_prime(bits)
while q == p:
q = generate_prime(bits)
# 2. Compute n = p * q
n = p * q
# 3. Compute φ(n) = (p - 1) * (q - 1)
phi = (p - 1) * (q - 1)
# 4. Choose public exponent e
e = 65537
if gcd(e, phi) != 1:
# rare, but handle by picking a different e
e = 3
while gcd(e, phi) != 1:
e += 2
# 5. Compute private exponent d = e^{-1} mod φ(n)
d = modinv(e, phi)
# Public key: (e, n), Private key: (d, n)
return (e, n), (d, n)
# ---------------------------------------
# RSA encryption / decryption
# ---------------------------------------
def message_to_int(message: str) -> int:
"""Convert string to integer."""
data = message.encode('utf-8')
return int.from_bytes(data, byteorder='big')
def int_to_message(m: int) -> str:
"""Convert integer back to string."""
length = (m.bit_length() + 7) // 8
data = m.to_bytes(length, byteorder='big')
return data.decode('utf-8', errors='ignore')
def rsa_encrypt(message: str, public_key):
e, n = public_key
m = message_to_int(message)
if m >= n:
raise ValueError("Message too long for this key size")
c = pow(m, e, n)
return c # ciphertext as integer
def rsa_decrypt(ciphertext: int, private_key):
d, n = private_key
m = pow(ciphertext, d, n)
return int_to_message(m)
# ---------------------------------------
# Example usage
# ---------------------------------------
if __name__ == "__main__":
# Generate keys (increase bits for stronger keys, but slower)
public_key, private_key = generate_rsa_keys(bits=256)
message = "Hello, RSA!"
print("Original message:", message)
ciphertext = rsa_encrypt(message, public_key)
print("Ciphertext (integer):", ciphertext)
decrypted = rsa_decrypt(ciphertext, private_key)
print("Decrypted message:", decrypted)
Run this script; it will:
- Generate a small RSA key pair.
- Encrypt
"Hello, RSA!" to an integer ciphertext.
- Decrypt it back to the original message.
You can adjust bits in generate_rsa_keys(bits=...) (e.g., 512, 1024) to change key size.