In [ ]:
# RSA cryptosystem
In [ ]:
# Base for powers = 17
# (Can use various numbers; 3 is also a common choice)
In [3]:
# Step 1: Alice chooses p,q 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
593
547
Out[3]:
1
In [6]:
# Step 2: compute private key e
# 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]; print(e)
57041
In [7]:
# (Don't need to do each time) Test if e is inverse to 17
(17*e) % ((p-1)*(q-1))
Out[7]:
1
In [10]:
# Step 3: Alice publishes public key
n = p*q; print(n) # publishes n, but does NOT publish p,q 
324371
In [12]:
# Step 4: Bob encrypts message m=111 (m should be less than n, also not super small)
m = 111 
c = power_mod(m,17,n); print(c) # This is the ciphertext. Bob sends to Alice
202530
In [13]:
# Step 5: Alice decrypts c using her private key e (as well as the public key n)
power_mod(c,e,n)
Out[13]:
111
In [ ]:
# message padding: add random bits to end of m for security