Lesson 15 of 15
RSA Encryption Basics
RSA Encryption
RSA (Rivest–Shamir–Adleman, 1977) is the most widely used public-key cryptosystem. Its security rests on the difficulty of factoring large numbers.
Key Generation
Given two distinct primes and :
- Compute (the modulus)
- Compute (Euler's totient)
- Choose with and (the public exponent)
- Compute using the Extended Euclidean Algorithm (the private exponent)
The public key is . The private key is .
Classic Example
With , , :
Encryption & Decryption
Both operations use fast modular exponentiation:
def rsa_encrypt(msg_int, e, n):
result = 1
base = msg_int % n
exp = e
while exp > 0:
if exp % 2 == 1:
result = (result * base) % n
exp //= 2
base = (base * base) % n
return result
def rsa_decrypt(cipher_int, d, n):
result = 1
base = cipher_int % n
exp = d
while exp > 0:
if exp % 2 == 1:
result = (result * base) % n
exp //= 2
base = (base * base) % n
return result
# Encrypt message 42 with public key (17, 3233)
cipher = rsa_encrypt(42, 17, 3233) # 2557
msg = rsa_decrypt(2557, 2753, 3233) # 42
Why It Works
By Euler's theorem: , so .
Modular Inverse via Extended GCD
def mod_inverse(e, phi):
def extended_gcd(a, b):
if b == 0: return a, 1, 0
g, x, y = extended_gcd(b, a % b)
return g, y, x - (a // b) * y
g, x, _ = extended_gcd(e, phi)
return x % phi # ensure positive
d = mod_inverse(17, 3120) # 2753
Your Task
Implement:
mod_inverse(e, phi)using extended GCD — returnsrsa_encrypt(msg_int, e, n)— returnsrsa_decrypt(cipher_int, d, n)— returns
Python runtime loading...
Loading...
Click "Run" to execute your code.