Okay, here is a Python script demonstrating the RSA algorithm from scratch.
This script implements the core mathematical operations needed for RSA key generation, encryption, and decryption. It does not use high-level cryptographic libraries like cryptography or PyCryptodome for the core RSA logic, focusing on implementing the underlying math (GCD, modular inverse, primality testing, modular exponentiation - though we use Python's built-in pow for the latter as it's optimized and standard).
Important Notes:
- Educational Purposes Only: This script is for demonstration and educational purposes. The primality test used is too slow for large numbers, the prime generation is basic, and there's no padding scheme implemented. DO NOT use this code for actual secure communication. Real-world RSA uses much larger primes, sophisticated prime generation methods, robust padding schemes (like OAEP), and optimized implementations.
- Integer Messages: This script works with messages represented as integers. In practice, messages (strings, files) are converted to integers using specific encoding and padding schemes before encryption.
- Key Size: The primes
p and q in the demonstration section are small to keep the numbers manageable for explanation. Real-world RSA uses primes large enough to result in n being 2048 bits, 3072 bits, or more.
import random
import math
# --- Helper Functions ---
def gcd(a, b):
"""
Calculates the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm.
This is needed to find 'e' and to calculate the modular inverse for 'd'.
The property gcd(a, b) = gcd(b, a % b) is used recursively until b becomes 0.
"""
while b != 0:
# The tuple assignment (a, b) = (b, a % b) simultaneously updates a and b
# a becomes the old b, and b becomes the old a % b
a, b = b, a % b
return a
def is_prime(num):
"""
Checks if a number is prime using a simple, trial division method.
For demonstration purposes. Not efficient for very large numbers required for secure RSA.
A number is prime if it is greater than 1 and has no positive divisors other than 1 and itself.
"""
# Numbers less than 2 are not prime
if num < 2:
return False
# 2 is the only even prime number
if num == 2:
return True
# All other even numbers are not prime
if num % 2 == 0:
return False
# Check for odd divisors from 3 up to the square root of the number.
# We only need to check up to the square root because if a number n has a divisor d > sqrt(n),
# then it must also have a divisor n/d < sqrt(n), which we would have already found.
# We increment by 2 because we've already handled even numbers.
i = 3
while i * i <= num:
if num % i == 0:
return False # Found a divisor, so not prime
i += 2
# If no divisors were found, the number is prime
return True
def mod_inverse(a, m):
"""
Calculates the modular inverse of 'a' modulo 'm' using the Extended Euclidean Algorithm.
The modular inverse 'x' of 'a' modulo 'm' is an integer such that (a * x) % m == 1.
It exists if and only if 'a' and 'm' are coprime (i.e., gcd(a, m) == 1).
The Extended Euclidean Algorithm finds integers x and y such that ax + my = gcd(a, m).
If gcd(a, m) == 1, then ax + my = 1. Taking this equation modulo m gives ax ≡ 1 (mod m),
so x is the modular inverse. The result is taken modulo m to be in the range [0, m-1].
"""
# We need to keep track of the coefficients (x, y) at each step of the Euclidean algorithm.
# We use an iterative version of the Extended Euclidean Algorithm.
# (g, x, y) starts with (a, 1, 0) and (m, 0, 1) corresponding to the equations
# a * 1 + m * 0 = a and a * 0 + m * 1 = m
g, x, y = a, 1, 0
g_prime, x_prime, y_prime = m, 0, 1
while g_prime != 0:
# Calculate the quotient of g divided by g_prime
quotient = g // g_prime
# Update g, x, y using the relationship from the Euclidean algorithm:
# new_g = g - quotient * g_prime
# new_x = x - quotient * x_prime
# new_y = y - quotient * y_prime
# We swap (g, x, y) with (g_prime, x_prime, y_prime) after updating
g, (x, y), g_prime, (x_prime, y_prime) = g_prime, (x_prime, y_prime), g - quotient * g_prime, (x - quotient * x_prime, y - quotient * y_prime)
# After the loop, g contains the GCD of the original a and m.
# If gcd(a, m) is not 1, the modular inverse does not exist.
if g != 1:
# This should not happen if 'a' (which is 'e') is chosen correctly such that gcd(e, phi) == 1.
raise ValueError(f"Modular inverse does not exist. gcd({a}, {m}) is {g}")
else:
# x is the modular inverse. We return it modulo m to get a result in the range [0, m-1].
return (x % m + m) % m
# --- RSA Core Functions ---
def generate_keypair(p, q):
"""
Generates an RSA public and private key pair.
Steps:
1. Choose two large, distinct prime numbers, p and q. (Handled by input validation).
2. Calculate n = p * q. This is the modulus for both the public and private keys.
3. Calculate phi = (p-1) * (q-1). This is Euler's totient function, representing
the number of positive integers less than n that are coprime to n.
4. Choose an integer 'e' such that 1 < e < phi and gcd(e, phi) == 1. 'e' is the public exponent.
Common choices are 65537, but any valid e works. We pick a random one here for demo.
5. Calculate 'd' such that d * e ≡ 1 (mod phi). 'd' is the private exponent.
'd' is the modular multiplicative inverse of 'e' modulo 'phi'.
"""
# Input validation: p and q must be distinct primes
if not (is_prime(p) and is_prime(q)):
raise ValueError("Both numbers must be prime.")
if p == q:
raise ValueError("p and q must be distinct primes.")
# 1. Calculate n = p * q
n = p * q
print(f"\nStep 1 (KeyGen): Calculate n = p * q = {p} * {q} = {n}")
# 2. Calculate phi = (p-1) * (q-1)
phi = (p - 1) * (q - 1)
print(f"Step 2 (KeyGen): Calculate phi = (p-1)*(q-1) = ({p-1})*({q-1}) = {phi}")
# 3. Choose e: Find an integer e such that 1 < e < phi and gcd(e, phi) == 1
# A common choice is 65537. Let's pick a random one for the demo.
# We need to ensure gcd(e, phi) is 1. We can check potential values of e.
e = random.randrange(2, phi) # Pick a random number between 2 and phi-1
while gcd(e, phi) != 1:
e = random.randrange(2, phi)
print(f"Step 3 (KeyGen): Choose e such that 1 < e < phi and gcd(e, phi) == 1.")
print(f" Chosen e = {e}")
print(f" Verification: gcd({e}, {phi}) = {gcd(e, phi)}")
# 4. Calculate d: Find an integer d such that d * e ≡ 1 (mod phi)
# d is the modular multiplicative inverse of e modulo phi
d = mod_inverse(e, phi)
print(f"Step 4 (KeyGen): Calculate d such that d * e ≡ 1 (mod phi).")
print(f" d is the modular inverse of {e} mod {phi}.")
print(f" Calculated d = {d}")
print(f" Verification: ({d} * {e}) % {phi} = {(d*e) % phi}")
# The public key is (e, n)
# The private key is (d, n)
print(f"\nPublic Key (e, n): ({e}, {n})")
print(f"Private Key (d, n): ({d}, {n})")
return ((e, n), (d, n))
def encrypt(public_key, plaintext_int):
"""
Encrypts an integer plaintext message using the recipient's public key.
Ciphertext C = M^e mod n
'plaintext_int' must be an integer representation of the message,
and 0 <= plaintext_int < n.
"""
e, n = public_key
print(f"\n--- Encryption ---")
print(f"Public Key (e, n): ({e}, {n})")
print(f"Plaintext (as integer): {plaintext_int}")
# The core encryption calculation: C = M^e mod n
# Python's built-in pow(base, exp, mod) is highly optimized for modular exponentiation.
ciphertext = pow(plaintext_int, e, n)
print(f"Encryption: C = M^e mod n = {plaintext_int}^{e} mod {n}")
print(f"Ciphertext: {ciphertext}")
return ciphertext
def decrypt(private_key, ciphertext):
"""
Decrypts an integer ciphertext using the recipient's private key.
Plaintext M = C^d mod n
"""
d, n = private_key
print(f"\n--- Decryption ---")
print(f"Private Key (d, n): ({d}, {n})")
print(f"Ciphertext: {ciphertext}")
# The core decryption calculation: M = C^d mod n
# Python's built-in pow(base, exp, mod) is highly optimized for modular exponentiation.
decrypted_plaintext_int = pow(ciphertext, d, n)
print(f"Decryption: M = C^d mod n = {ciphertext}^{d} mod {n}")
print(f"Decrypted Plaintext (as integer): {decrypted_plaintext_int}")
return decrypted_plaintext_int
# --- Demonstration ---
if __name__ == "__main__":
print("--- RSA Algorithm Demonstration ---")
# 1. Choose two distinct prime numbers, p and q.
# These are small for demonstration. In practice, they would be very large.
p = 61
q = 53
print(f"Chosen primes p = {p} and q = {q}")
# Verify they are prime and distinct (the generate_keypair function does this too)
if not is_prime(p):
print(f"Error: p={p} is not prime.")
if not is_prime(q):
print(f"Error: q={q} is not prime.")
if p == q:
print(f"Error: p={p} and q={q} must be distinct.")
# 2. Generate Public and Private Keys
# The function returns ((e, n), (d, n))
public_key, private_key = generate_keypair(p, q)
# 3. Prepare a Message
# The message must be an integer M such that 0 <= M < n
# In a real application, strings are converted to integers using padding schemes.
# Let's use a simple integer message for this demo.
message_int = 12345 # Example message (integer)
n = public_key[1] # Get n from the public key
if not (0 <= message_int < n):
print(f"\nError: Message integer {message_int} is not in the valid range [0, {n-1}).")
# Adjust the message if needed for the demo
if message_int >= n:
message_int = message_int % n # Simple fix for demo, not secure padding!
print(f"Adjusting message for demo: {message_int}")
# 4. Encrypt the Message
ciphertext = encrypt(public_key, message_int)
# 5. Decrypt the Ciphertext
decrypted_message_int = decrypt(private_key, ciphertext)
# 6. Verify Decryption
print(f"\n--- Verification ---")
print(f"Original Message (int): {message_int}")
print(f"Decrypted Message (int): {decrypted_message_int}")
if message_int == decrypted_message_int:
print("Verification Successful: Decrypted message matches original message.")
else:
print("Verification Failed: Decrypted message DOES NOT match original message.")
print("\n--- End of Demonstration ---")