If p or q is not prime, it is rounded to the nearest prime. e must satisfy gcd(e, phi(n)) = 1.
Left = key pair (n, φ, e, d) / right = encryption flow m → [^e mod n] → c → [^d mod n] → m'
RSA is a public-key cryptosystem whose security rests on the difficulty of integer factorization. The key generation steps are:
Pick two primes p and q, then form the modulus and Euler's totient:
$$n = p\,q, \qquad \varphi(n) = (p-1)(q-1)$$Choose the public exponent e coprime with φ(n) (gcd(e, φ(n)) = 1). The private exponent d is the modular inverse of e modulo φ(n), found with the extended Euclidean algorithm:
$$e\,d \equiv 1 \pmod{\varphi(n)}$$Encryption and decryption are both modular exponentiations modulo n:
$$c = m^{e} \bmod n, \qquad m' = c^{d} \bmod n$$A precondition is 0 ≤ m < n. By Fermat–Euler, the round trip recovers m' = m.