# RSA Algorithm Implementation from Scratch
# This script demonstrates the RSA public-key cryptosystem, including key generation,
# encryption, and decryption. RSA is an asymmetric encryption algorithm that uses
# two keys: a public key for encryption and a private key for decryption.
#
# Key Concepts:
# 1. **Prime Numbers**: RSA relies on the difficulty of factoring the product of two large primes.
# 2. **Modular Arithmetic**: All operations are performed modulo n, where n is the product of two primes.
# 3. **Euler's Totient Function**: Used to ensure the public exponent e is coprime with φ(n).
# 4. **Modular Inverse**: The private exponent d is the inverse of e modulo φ(n).
#
# For security, RSA uses very large primes (e.g., 1024+ bits), but for this demonstration,
# we'll use small primes to keep it simple and fast. This is NOT secure for real-world use.
#
# Steps in RSA:
# - Generate two distinct prime numbers, p and q.
# - Compute n = p * q (part of both public and private keys).
# - Compute φ(n) = (p-1) * (q-1).
# - Choose e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1 (e and φ(n) are coprime).
# - Compute d such that (e * d) % φ(n) = 1 (d is the modular inverse of e modulo φ(n)).
# - Public key: (e, n)
# - Private key: (d, n)
# - Encryption: c = (m^e) % n
# - Decryption: m = (c^d) % n
#
# Note: We'll use Python's built-in functions for efficiency, but implement helper functions from scratch.
import math # For mathematical functions like gcd
import random # For generating random numbers
# Function to check if a number is prime
# A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
def is_prime(num):
"""
Checks if a given number is prime using trial division.
Args:
num (int): The number to check.
Returns:
bool: True if num is prime, False otherwise.
Explanation:
- We only need to check divisors up to the square root of num because if num has a factor larger than its square root,
it must also have a factor smaller than the square root.
- This is a simple primality test; for large numbers, more advanced tests like Miller-Rabin are used.
"""
if num <= 1:
return False # Numbers less than or equal to 1 are not prime
if num <= 3:
return True # 2 and 3 are prime
if num % 2 == 0 or num % 3 == 0:
return False # Multiples of 2 and 3 are not prime
i = 5
while i * i <= num:
if num % i == 0 or num % (i + 2) == 0:
return False # If num is divisible by i or i+2, it's not prime
i += 6 # Check numbers of the form 6k ± 1, as all primes > 3 are of this form
return True
# Function to generate a random prime number
def generate_prime(bits=10):
"""
Generates a random prime number with approximately the specified number of bits.
Args:
bits (int): The approximate number of bits for the prime (e.g., 10 for a number around 2^10 = 1024).
Returns:
int: A random prime number.
Explanation:
- We generate random odd numbers in the range [2^(bits-1), 2^bits) and check if they are prime.
- This is a simple method; in practice, for large primes, you'd use more efficient probabilistic tests.
"""
while True:
# Generate a random number in the desired range
num = random.randrange(2**(bits-1), 2**bits)
if num % 2 != 0 and is_prime(num): # Ensure it's odd and prime
return num
# Function to compute the greatest common divisor (GCD) using Euclidean algorithm
# This is used to check if e and φ(n) are coprime.
def gcd(a, b):
"""
Computes the greatest common divisor of a and b using the Euclidean algorithm.
Args:
a (int): First number.
b (int): Second number.
Returns:
int: The GCD of a and b.
Explanation:
- The Euclidean algorithm works by repeatedly applying: gcd(a, b) = gcd(b, a % b) until b is 0.
- This is a fundamental step in ensuring e is coprime with φ(n).
"""
while b:
a, b = b, a % b
return a
# Function to compute the modular inverse using Extended Euclidean Algorithm
def modular_inverse(e, phi):
"""
Computes the modular inverse of e modulo phi using the Extended Euclidean Algorithm.
Args:
e (int): The number to find the inverse for.
phi (int): The modulus.
Returns:
int: The modular inverse d such that (e * d) % phi == 1.
Raises:
ValueError: If no inverse exists (i.e., e and phi are not coprime).
Explanation:
- The Extended Euclidean Algorithm not only computes gcd(a, b) but also finds coefficients x and y
such that a*x + b*y = gcd(a, b).
- For modular inverse, we solve for x in e*x ≡ 1 mod phi, which requires gcd(e, phi) == 1.
"""
def extended_gcd(a, b):
if a == 0:
return b, 0, 1
gcd_val, x1, y1 = extended_gcd(b % a, a)
x = y1 - (b // a) * x1
y = x1
return gcd_val, x, y # Returns gcd, x, y where a*x + b*y = gcd
gcd_val, x, _ = extended_gcd(e, phi)
if gcd_val != 1:
raise ValueError("Modular inverse does not exist; e and phi are not coprime.")
return x % phi # x is the inverse, but we take it modulo phi to keep it positive
# Function to generate RSA keys
def generate_keys():
"""
Generates a pair of RSA keys: public key (e, n) and private key (d, n).
Returns:
tuple: (public_key, private_key) where public_key = (e, n) and private_key = (d, n).
Explanation:
- First, generate two distinct prime numbers p and q.
- Compute n = p * q.
- Compute φ(n) = (p-1) * (q-1).
- Choose e as a small number (e.g., 65537) that is coprime with φ(n).
- Compute d as the modular inverse of e modulo φ(n).
"""
p = generate_prime() # Generate first prime
q = generate_prime() # Generate second prime
while q == p: # Ensure p and q are distinct
q = generate_prime()
n = p * q # Compute n
phi = (p - 1) * (q - 1) # Compute Euler's totient
e = 65537 # Common choice for e; it's a prime and likely coprime with phi
while gcd(e, phi) != 1: # Ensure e and phi are coprime
e -= 2 # Try a smaller e if needed (though 65537 usually works)
d = modular_inverse(e, phi) # Compute d
public_key = (e, n) # Public key: (e, n)
private_key = (d, n) # Private key: (d, n)
return public_key, private_key
# Function to encrypt a message
def encrypt(message, public_key):
"""
Encrypts a message using the public key.
Args:
message (int): The plaintext message (must be an integer between 0 and n-1).
public_key (tuple): The public key (e, n).
Returns:
int: The ciphertext.
Explanation:
- Compute c = (message^e) % n.
- We use Python's built-in pow() for efficient modular exponentiation.
"""
e, n = public_key
if not 0 <= message < n:
raise ValueError("Message must be between 0 and n-1.")
ciphertext = pow(message, e, n) # Modular exponentiation
return ciphertext
# Function to decrypt a ciphertext
def decrypt(ciphertext, private_key):
"""
Decrypts a ciphertext using the private key.
Args:
ciphertext (int): The encrypted message.
private_key (tuple): The private key (d, n).
Returns:
int: The original plaintext message.
Explanation:
- Compute m = (ciphertext^d) % n.
- This works because of RSA's mathematical properties: (m^e)^d ≡ m mod n.
"""
d, n = private_key
plaintext = pow(ciphertext, d, n) # Modular exponentiation
return plaintext
# Main demonstration
if __name__ == "__main__":
print("Demonstrating RSA Algorithm:")
# Generate keys
public_key, private_key = generate_keys()
e, n = public_key
d, _ = private_key # We don't need n here again, but it's the same
print(f"Generated Public Key: (e = {e}, n = {n})")
print(f"Generated Private Key: (d = {d}, n = {n})")
# Choose a simple message (must be less than n)
message = 42 # Example plaintext; in practice, you'd convert text to a number
print(f"\nOriginal Message: {message}")
# Encrypt the message
ciphertext = encrypt(message, public_key)
print(f"Encrypted Ciphertext: {ciphertext}")
# Decrypt the ciphertext
decrypted_message = decrypt(ciphertext, private_key)
print(f"Decrypted Message: {decrypted_message}")
# Verify
if decrypted_message == message:
print("\nDecryption successful! The RSA algorithm works as expected.")
else:
print("\nError: Decryption failed.")
print("\nNote: This is a simplified demonstration with small primes. In real-world RSA,")
print("use much larger primes (e.g., 2048 bits) to ensure security.")
This script is fully self-contained and explains each part of the RSA algorithm step by step. Run it to see the output, which will generate keys, encrypt a message, and decrypt it. Remember, this is for educational purposes only—real RSA implementations use much larger numbers for security.