Application: Cryptography
Matrix arithmetic modulo a number gives a neat classical cipher, the Hill cipher (Lester Hill, 1929): split a message into blocks of letters, treat each block as a vector, and multiply by a secret key matrix mod 26. Decryption multiplies by the inverse matrix. It is a great exercise in Matrix Arithmetic Modulo p, and an equally good lesson in why linear encryption is insecure.
Letters as numbers
Number the letters and work in . A message is cut into blocks of letters, each a vector in (pad the end with X if needed). With , "HELP" becomes the vectors and .
Encryption and decryption
Choose an key matrix with entries in . Each plaintext block becomes the ciphertext block
and the receiver recovers it with
The catch: is not prime, so is not a field and not every non-zero number has an inverse. is invertible mod 26 exactly when is coprime to 26, i.e. odd and not a multiple of 13. Then
For our key : , and , so and .
from sympy import Matrix
from math import gcd
def to_nums(s): return [ord(ch) - 65 for ch in s]
def to_text(v): return "".join(chr(int(x) + 65) for x in v)
def hill(text, K, n=2):
text += "X" * (-len(text) % n) # pad to a multiple of n
out = []
for i in range(0, len(text), n):
block = Matrix(to_nums(text[i:i + n]))
out += list((K * block) % 26)
return to_text(out)
def inv_mod26(K): # adjugate formula; works for composite 26
return (K.adjugate() * pow(int(K.det()), -1, 26)) % 26
K = Matrix([[5, 8], [17, 3]])
print("det K mod 26:", K.det() % 26, " coprime to 26:", gcd(int(K.det() % 26), 26) == 1)
Kinv = inv_mod26(K)
print("K^-1 mod 26:", Kinv.tolist())
cipher = hill("MEETATNOON", K)
print("cipher:", cipher)
print("plain :", hill(cipher, Kinv))det K mod 26: 9 coprime to 26: True
K^-1 mod 26: [[9, 2], [1, 15]]
cipher: OIQVWFVDSR
plain : MEETATNOON
Because each output letter depends on a whole block, the Hill cipher hides single-letter frequencies better than a Caesar shift: the two E's of "MEET" sit in different blocks (ME → OI, ET → QV) and come out as different letters, I and Q.
Choosing a valid key
A random 2×2 matrix mod 26 is invertible only about a third of the time ( must avoid all even numbers and 13). Checking the determinant is the whole test:
import numpy as np
from math import gcd
rng = np.random.default_rng(7)
trials, good = 2000, 0
for _ in range(trials):
a, b, c, d = (int(v) for v in rng.integers(0, 26, size=4))
if gcd((a * d - b * c) % 26, 26) == 1:
good += 1
print(f"invertible keys: {good}/{trials} = {good / trials:.1%}")invertible keys: 712/2000 = 35.6%
(The exact fraction for 2×2 matrices is ; the simulation is close.)
Why the Hill cipher is broken
The cipher is linear, and linear algebra breaks it. Suppose an attacker knows (or guesses) two plaintext blocks and their ciphertexts , a known-plaintext attack (messages often start with predictable words such as a greeting or a header). Put them side by side as columns:
Two blocks reveal the whole 2×2 key; for keys, blocks suffice. The attack is one matrix inverse and one product:
from sympy import Matrix
from math import gcd
def nums(s): return [ord(ch) - 65 for ch in s]
def inv_mod26(M): return (M.adjugate() * pow(int(M.det()), -1, 26)) % 26
plain, cipher = "MEETATNOON", "OIQVWFVDSR" # intercepted pair from above
blocks = [(plain[i:i+2], cipher[i:i+2]) for i in range(0, len(plain), 2)]
for (p1, c1) in blocks:
for (p2, c2) in blocks:
P = Matrix([nums(p1), nums(p2)]).T # plaintext blocks as columns
if gcd(int(P.det() % 26), 26) == 1:
C = Matrix([nums(c1), nums(c2)]).T
K = (C * inv_mod26(P)) % 26
print("used blocks", p1, p2, "-> recovered key", K.tolist())
break
else:
continue
breakused blocks ET NO -> recovered key [[5, 8], [17, 3]]
Note: Never use the Hill cipher (or any home-made cipher) to protect real data. It falls to known-plaintext attacks in milliseconds. Real systems use vetted algorithms such as AES-GCM or ChaCha20-Poly1305 through a well-reviewed library (Symmetric Encryption).
In software
- Linearity is the weakness. Modern block ciphers still use linear layers for diffusion (AES's MixColumns is a 4×4 matrix over the field ), but they interleave them with non-linear S-boxes so that no matrix equation like exists.
- Lattice cryptography: post-quantum schemes such as ML-KEM (Kyber, standardised by NIST in 2024) are built on matrices mod , made secure by adding small random noise (the learning-with-errors problem). Without the noise, Gaussian elimination would break them just like the Hill cipher.
- Secret sharing and coding: Shamir secret sharing and Reed–Solomon codes solve linear (Vandermonde) systems over finite fields; see Cryptography Basics for the wider landscape.
Exercises
Exercise 1: Encrypt by hand
With , encrypt the block "HI" (, ).
Answer
"HI" → → "VN".
Solution
Exercise 2: Is this a valid key?
Which of these keys can be used: , , ?
Answer
and are valid keys; is not.
Solution
Exercise 3: Inverse key by formula
Find the inverse mod 26 of .
Answer
.
Solution
Check with code:
from sympy import Matrix
K = Matrix([[2, 3], [1, 4]])
X = Matrix([[6, 15], [5, 16]])
print(((K * X) % 26).tolist(), ((K.adjugate() * pow(5, -1, 26)) % 26).tolist())[[1, 0], [0, 1]] [[6, 15], [5, 16]]
Exercise 4: Break a message
You intercept the ciphertext "DRDCKF" and know the message starts with "HELLO". Recover the 2×2 key with the attack above and decrypt the whole message.
Answer
The code below recovers the key from the blocks "HE" and "LL" and decrypts the message to "HELLOX" ("HELLO" padded with X).
Solution
The blocks HE → DR and LL → DC give (, coprime to 26), so .
from sympy import Matrix
def nums(s): return [ord(ch) - 65 for ch in s]
def inv_mod26(M): return (M.adjugate() * pow(int(M.det()), -1, 26)) % 26
P = Matrix([nums("HE"), nums("LL")]).T
C = Matrix([nums("DR"), nums("DC")]).T
K = (C * inv_mod26(P)) % 26
print("key:", K.tolist())
Kinv = inv_mod26(K)
ct = "DRDCKF"
pt = "".join(chr(int(v) + 65) for i in range(0, 6, 2)
for v in (Kinv * Matrix(nums(ct[i:i+2]))) % 26)
print("plaintext:", pt)key: [[3, 2], [7, 5]]
plaintext: HELLOX
Test yourself
When is a key matrix usable for the Hill cipher mod 26?
- When
- When is coprime to 26
- When is symmetric
- When all entries are below 13
How many known plaintext/ciphertext blocks are typically enough to recover a 3×3 Hill key?
- 3
- 1
- 9
- 26
What do modern ciphers like AES add that the Hill cipher lacks?
- Bigger matrices only
- Longer alphabets
- Matrices modulo a prime
- Non-linear S-boxes, so no linear equation recovers the key