Vertopal.com Assignment
Vertopal.com Assignment
(simplified version)
Key generation
• Pick any two prime numbers namely p and q
• Calculate n=p q. Here n is called the modulus.
• Calculate ϕ ( n )= ( p − 1 )( q − 1 ).
• Choose 1<e <ϕ ( n ) such that e and ϕ ( n ) are coprime. Here e is called the exponent.
• Find 1<d <n such that e d ≡ 1(mod ϕ ( n ) ). Here d is called the private key.
Key distribution
• The modulus and the exponent are called the public key. They are used to encrypt any
message. So distribute them.
• The modulus and the private key are used to decrypt the encrypted message. So keep
secret.
Actually this keys are not secure because the strength of RSA algorithm lies behind the
calculation difficulty of d from n and e only. And this is not possinle when the number n is not
large enought.
For example to encrypt the number x=20 using the public key e=3 , you need to calculate
Implementation
1. Complete the implementation of encryption and decryption functions in Python.
2. Find different public and private keys and test your implementation with these keys.
3. Try to implement the key generation process. What are the difficulties?
def encrypt(x, n=33, e=3):
return pow(x, e, n)
assert 18 == decrypt(encrypt(18))
public_key, private_key = generate_keys()
print("Public key:", public_key)
print("Private key:", private_key)
x = 18
y = encrypt(x, public_key[0], public_key[1])
print("Encrypted: ", y)
assert z == x
assert 18 == decrypt(encrypt(18))
import random
def generate_keys():
p = random.randint(1, 100)
q = random.randint(1, 100)
while not (is_prime(p) and is_prime(q)):
p = random.randint(1, 100)
q = random.randint(1, 100)
n = p * q
phi_n = (p - 1) * (q - 1)
e = random.randint(1, phi_n)
while gcd(e, phi_n) != 1:
e = random.randint(1, phi_n)
return n, e, d
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
n, e, d = generate_keys()
assert 18 == decrypt(encrypt(18, n, e), d, n)