In [ ]:
# RSA cryptosystem for public-key cryptography
In [ ]:
# Base for powers = 17
# (Can use various numbers; 3 is also a common choice)
In [3]:
# Step 1: Alice makes a public and private key
# (a)
# First generate two large primes p,q (should be much larger than below in practice)
p=next_prime(randint(500,1000)); print(p)
q=next_prime(randint(500,1000)); print(q)
gcd(17, (p-1)*(q-1)) # if not 1, rechoose p,q
821
881
Out[3]:
1
In [11]:
n = p*q; print(n) # Alice publishes n as public key
723301
In [8]:
# (b) compute private key e, the inverse of 17 mod (p-1)(q-1)
# This uses Extended Euclidean algorithm, which outputs
# a triple of numbers, the middle of which is the invere 
e=xgcd(17,(p-1)*(q-1))[1] % ((p-1)*(q-1)); print(e)
679153
In [9]:
# check xgcd is used properly (don't really need)
# this should be 1
(17*e) % ((p-1)*(q-1))
Out[9]:
1
In [12]:
# Step 2: Bob encrypts message m = 111, using public key n
# (m should be less than n, but also not super small)
m=111
c=power_mod(m,17,n); print(c) # This is the ciphertext. Bob sends to Alice
64629
In [13]:
# Step 3: Alice decrypts c using private key e
power_mod(c,e,n)
Out[13]:
111
In [ ]: