Encrypting "hello"
Let's encrypt something like "hello" using RSA.
Step 1: Convert "hello" to a number
We use a basic scheme like ASCII:
python
CopyEdit
"hello" → [104, 101, 108, 108, 111] # ASCII codes
Let's just take the number 104 (which is 'h') to walk through the encryption.
Step 2: Encrypt with public key (e, n)
The encrypted value c is:
python
CopyEdit
c = (m ** e) % n
Where:
m is the plaintext number (e.g. 104)
e and n are from the public key
💡 This works because exponentiation and modulo math are easy to compute in one direction but hard to reverse without the private key.
🔓 Decryption
To decrypt the ciphertext c, you use the private key (d, n):
python
CopyEdit
m = (c ** d) % n
This brings back the original number m (like 104), which you then convert back to a character: 'h'.
🧬 Can you see the pattern between public and private keys?
Yes, kind of.
Both share n
e and d are modular inverses with respect to φ(n)
You cannot see p and q directly from n, unless you factor it (which is very hard if n is 2048-bit+)
So while there's a mathematical relationship, it's computationally infeasible to reverse-engineer d from e and n without factoring n.
🔁 Full Flow Summary
plaintext
CopyEdit
1. Sender encrypts with public key: c = (m^e) mod n
2. Receiver decrypts with private key: m = (c^d) mod n
🧪 Code Example (Python - Using small primes for demo)
python
CopyEdit
# Super simple demo, not secure primes
p = 61
q = 53
n = p * q # 3233
phi = (p - 1) * (q - 1) # 3120
e = 17 # Chosen as public exponent
# Find d such that (d * e) % phi == 1
def modinv(e, phi):
for d in range(1, phi):
if (d * e) % phi == 1:
return d
return None
d = modinv(e, phi)
# Encrypt a character (say 'h' = 104)
m = 104
c = pow(m, e, n)
print("Encrypted:", c) # ciphertext
# Decrypt
decrypted = pow(c, d, n)
print("Decrypted:", chr(decrypted)) # back to 'h'
🔐 Why Is RSA So Powerful?
Easy to encrypt with a public key.
Only someone with the private key can decrypt.
Secure even if everyone knows your public key.
Based on hard math (factoring large primes).