↓ Skip to main content

Part 2: The Story of RSA-8

·447 words·3 mins·
Table of Contents
RSA-8 - This article is part of a series.
Part 2: This Article
Encrypting & decrypting with our public and private keys.

In Part 1 we created this deliberately tiny RSA key pair:

p = 11
q = 13
n = 143
phi(n) = 120

e = 7
d = 103

Public key  = (7, 143)
Private key = (103, 143)

Now we can actually use it.

Important: This is textbook RSA for education only. Real applications require secure key generation, established cryptographic libraries, and appropriate padding schemes.

Encrypt A Message
#

Let our plaintext message be the integer:

m = 9

RSA encryption is:

c = m^e mod n

Substitute our values:

c = 9^7 mod 143
  = 48

So:

Plaintext  = 9
Ciphertext = 48

Decrypt it
#

RSA decryption is:

m = c^d mod n

Using our private key:

m = 48^103 mod 143
  = 9

The original message is recovered.

message = 9
    |
    | public key (7,143)
    v
9^7 mod 143
    |
    v
ciphertext = 48
    |
    | private key (103,143)
    v
48^103 mod 143
    |
    v
message = 9

In Python
#

# Tiny RSA demonstration
# Educational only. This is NOT secure RSA.

# 1. Choose two small prime numbers
p = 11
q = 13

print("p =", p)
print("q =", q)

# 2. Calculate the modulus
n = p * q
print("n =", n)
print("n bit length =", n.bit_length())

# 3. Calculate Euler's totient
phi = (p - 1) * (q - 1)
print("phi(n) =", phi)

# 4. Choose the public exponent
e = 7

# 5. Calculate the private exponent.
# Python finds the modular inverse of e modulo phi(n).
d = pow(e, -1, phi)

print()
print("Public key  =", (e, n))
print("Private key =", (d, n))

# 6. Encrypt
message = 9
ciphertext = pow(message, e, n)

print()
print("Original message:", message)
print("Ciphertext:", ciphertext)

# 7. Decrypt
decrypted_message = pow(ciphertext, d, n)
print("Decrypted message:", decrypted_message)

Expected output:

p = 11
q = 13
n = 143
n bit length = 8
phi(n) = 120

Public key  = (7, 143)
Private key = (103, 143)

Original message: 9
Ciphertext: 48
Decrypted message: 9

Useful Operation
#

Python’s three-argument pow() performs modular exponentiation efficiently:

pow(base, exponent, modulus)

That maps directly onto RSA:

ciphertext = pow(message, e, n)
plaintext = pow(ciphertext, d, n)

And this line computes the modular inverse needed for our private exponent:

d = pow(e, -1, phi)

🔑 Key Takeaway
#

Encryption: c = m^e mod n
Decryption: m = c^d mod n

The public exponent e can be public. The private exponent d must remain secret.

But why can’t an attacker calculate d from the public information? With an 8-bit key, they absolutely can.

Part 3 deliberately attacks our own key.

MySeq
Author
MySeq
myseq.github.io
RSA-8 - This article is part of a series.
Part 2: This Article

Related