RSA Encryption
The world's most common , named after its founders: Rivest, Shamir, and Adleman.
Where it's used
RSA is found anywhere an protocol is needed, such as securing HTTPS connections via TLS/SSL certificates, authenticating SSH sessions, and encrypting email and software signatures through PGP/GPG.
Why it's used
Asymmetric encryption schemes like RSA involve a which anyone can see and use, and a only the holder can use. The inherent asymmetry eliminates the need to create a in advance. The security of RSA relies on the extreme difficulty of factoring the product of two large
1import random2▼3def is_probably_prime(n, k=20):4 """Miller-Rabin primality test."""▼5 if n < 2:6 return False▼7 if n == 2 or n == 3:8 return True▼9 if n % 2 == 0:10 return False1112 # Write n-1 as 2^r * d13 r, d = 0, n - 1▼14 while d % 2 == 0:15 r += 116 d //= 21718 # Witness loop▼19 for _ in range(k):20 a = random.randrange(2, n - 1)21 x = pow(a, d, n) # a^d mod n22▼23 if x == 1 or x == n - 1:24 continue25▼26 for _ in range(r - 1):27 x = pow(x, 2, n)▼28 if x == n - 1:29 break▼30 else:31 return False32 return True33▼34def generate_prime(bits=512):35 """Generate a random prime of given bit length."""▼36 while True:37 # Generate random odd number of correct bit length38 n = random.getrandbits(bits)39 n |= (1 << bits - 1) | 1 # Set MSB and LSB▼40 if is_probably_prime(n):41 return n4243p = generate_prime(512)44q = generate_prime(512)45print(f"p = {p}")46print(f"q = {q}")
Step 1 of 6
1. Generate Large Primes
Select two large random p and q. In practice these are 1024+ bits. We use a to probabilistically verify p and q are prime.
Create Public and Private Keys
- 1.Generate large primes p and q
- 2.Compute n = p × q and φ(n) = (p-1)(q-1)
- 3.Choose public exponent e = 65537
- 4.Derive private key d = e⁻¹ mod φ(n)