RSA generates a key from two primes, encrypts with the public exponent and decrypts with the private one. Your program runs the whole cycle for small primes, so you can see the message come back.
What to build
A program that makes an RSA key pair, encrypts a message and decrypts it.
Requirements
- Read p, q, e and m on one line: two primes, the public exponent and the message.
- Print
n:(p × q),phi:((p − 1)(q − 1)),d:(the inverse of e modulo phi),cipher:(m to the power e mod n) anddecrypted:(the cipher to the power d mod n).
Input
One line with p, q, e and m.
Output
Five lines.
Constraints
p and q are different primes below 200 (the case p = 2 is allowed); gcd(e, phi) = 1; 0 ≤ m < n.
Example
Input:
61 53 17 65
Output:
n: 3233
phi: 3120
d: 2753
cipher: 2790
decrypted: 65
Why it works
Encryption raises m to the power e and decryption raises the result to the power d. Because e × d leaves remainder 1 modulo phi, the two powers cancel (Euler's theorem), so the decrypted number equals the message. Computing d needs phi, which needs the primes p and q: that is why they stay secret.
Examples
61 53 17 65
n: 3233 phi: 3120 d: 2753 cipher: 2790 decrypted: 65
5 11 3 9
n: 55 phi: 40 d: 27 cipher: 14 decrypted: 9
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
n = p * q and phi = (p - 1) * (q - 1).
Hint 2
The private key is d = pow(e, -1, phi); encrypt with pow(m, e, n) and decrypt with pow(c, d, n).
Hint 3
The message m is smaller than n, and e is coprime to phi.
Solution
Show one correct solution (try it yourself first)
p, q, e, m = map(int, input().split())
n = p * q
phi = (p - 1) * (q - 1)
d = pow(e, -1, phi)
c = pow(m, e, n)
print("n:", n)
print("phi:", phi)
print("d:", d)
print("cipher:", c)
print("decrypted:", pow(c, d, n))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step