~/Writing Your Own RSA Encryption Scheme
May 18, 2022
RSA is a public key cryptography algorithm based on the difficulty of factoring large integers. To write your own scheme, follow these steps.
Key Generation
- Pick two large random primes
p
andq
. - Compute
n = p * q
. - Compute Euler’s totient
phi_n = (p - 1) * (q - 1)
. - Choose integer
e
such that1 < e < phi_n
, and gcd(e, phi_n) = 1, often 65537. - Calculate
d
, the modular inverse ofe
modulophi_n
.
The public key is (n, e)
and the private key is d
.
Encryption
To encrypt message m
, compute
c = m^e mod n
Decryption
To decrypt ciphertext c
, compute
m = c^d mod n
Example in Python
Security Notes
Never use small primes or implement RSA without cryptographic libraries like PyCryptodome. Always use padding such as OAEP for real systems.
For more details see Wikipedia RSA details.