TExcelTAD
Home › Linear Algebra & Matrix Theory › Application: Cryptography

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 A=0,B=1,…,Z=25\text{A} = 0, \text{B} = 1, \ldots, \text{Z} = 25 and work in Z26\mathbb{Z}_{26}. A message is cut into blocks of nn letters, each a vector in Z26n\mathbb{Z}_{26}^n (pad the end with X if needed). With n=2n = 2, "HELP" becomes the vectors [7,4][7, 4] and [11,15][11, 15].

Encryption and decryption

Choose an n×nn \times n key matrix KK with entries in Z26\mathbb{Z}_{26}. Each plaintext block p\mathbf{p} becomes the ciphertext block

c=Kp(mod26)\mathbf{c} = K\mathbf{p} \pmod{26}

and the receiver recovers it with

p=K−1c(mod26)\mathbf{p} = K^{-1}\mathbf{c} \pmod{26}

The catch: 26=2⋅1326 = 2 \cdot 13 is not prime, so Z26\mathbb{Z}_{26} is not a field and not every non-zero number has an inverse. KK is invertible mod 26 exactly when det⁡K\det K is coprime to 26, i.e. odd and not a multiple of 13. Then

K−1=(det⁡K)−1⋅adj⁡(K)(mod26),for 2×2:adj⁡[abcd]=[d−b−ca]K^{-1} = (\det K)^{-1} \cdot \operatorname{adj}(K) \pmod{26}, \qquad \text{for } 2 \times 2\text{:} \quad \operatorname{adj} \begin{bmatrix} a & b \\ c & d \end{bmatrix} = \begin{bmatrix} d & -b \\ -c & a \end{bmatrix}

For our key K=[58173]K = \begin{bmatrix} 5 & 8 \\ 17 & 3 \end{bmatrix}: det⁡K=15−136=−121≡9(mod26)\det K = 15 - 136 = -121 \equiv 9 \pmod{26}, and 9⋅3=27≡19 \cdot 3 = 27 \equiv 1, so (det⁡K)−1=3(\det K)^{-1} = 3 and K−1=3⋅[3−8−175]=[9−24−5115]≡[92115]K^{-1} = 3 \cdot \begin{bmatrix} 3 & -8 \\ -17 & 5 \end{bmatrix} = \begin{bmatrix} 9 & -24 \\ -51 & 15 \end{bmatrix} \equiv \begin{bmatrix} 9 & 2 \\ 1 & 15 \end{bmatrix}.

python · try it yourself
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 (det⁡\det must avoid all even numbers and 13). Checking the determinant is the whole test:

python · try it yourself
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 157 248/456 976≈34.4%157\,248 / 456\,976 \approx 34.4\%; 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 p1,p2\mathbf{p}_1, \mathbf{p}_2 and their ciphertexts c1,c2\mathbf{c}_1, \mathbf{c}_2, a known-plaintext attack (messages often start with predictable words such as a greeting or a header). Put them side by side as columns:

C=[c1 c2]=K [p1 p2]=KP⇒K=CP−1(mod26),if P is invertible mod 26C = [\mathbf{c}_1\ \mathbf{c}_2] = K\,[\mathbf{p}_1\ \mathbf{p}_2] = KP \quad \Rightarrow \quad K = CP^{-1} \pmod{26}, \quad \text{if } P \text{ is invertible mod 26}

Two blocks reveal the whole 2×2 key; for n×nn \times n keys, nn blocks suffice. The attack is one matrix inverse and one product:

python · try it yourself
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
    break
used 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 GF(28)\mathrm{GF}(2^8)), but they interleave them with non-linear S-boxes so that no matrix equation like K=CP−1K = CP^{-1} exists.
  • Lattice cryptography: post-quantum schemes such as ML-KEM (Kyber, standardised by NIST in 2024) are built on matrices mod qq, 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 K=[58173]K = \begin{bmatrix} 5 & 8 \\ 17 & 3 \end{bmatrix}, encrypt the block "HI" (H=7\text{H} = 7, I=8\text{I} = 8).

Answer

"HI" → [99,143]≡[21,13][99, 143] \equiv [21, 13] → "VN".

Solution
K⋅[7,8]=[5⋅7+8⋅8, 17⋅7+3⋅8]=[35+64, 119+24]=[99,143]99 mod 26=99−78=21→V;143 mod 26=143−130=13→N\begin{aligned} K \cdot [7, 8] &= [5 \cdot 7 + 8 \cdot 8,\ 17 \cdot 7 + 3 \cdot 8] = [35 + 64,\ 119 + 24] = [99, 143] \\ 99 \bmod 26 &= 99 - 78 = 21 \to \text{V}; \qquad 143 \bmod 26 = 143 - 130 = 13 \to \text{N} \end{aligned}

Exercise 2: Is this a valid key?

Which of these keys can be used: K1=[2314]K_1 = \begin{bmatrix} 2 & 3 \\ 1 & 4 \end{bmatrix}, K2=[3142]K_2 = \begin{bmatrix} 3 & 1 \\ 4 & 2 \end{bmatrix}, K3=[1237]K_3 = \begin{bmatrix} 1 & 2 \\ 3 & 7 \end{bmatrix}?

Answer

K1K_1 and K3K_3 are valid keys; K2K_2 is not.

Solution
det⁡K1=8−3=5gcd⁡(5,26)=1→validdet⁡K2=6−4=2gcd⁡(2,26)=2→invalid (even)det⁡K3=7−6=1gcd⁡(1,26)=1→valid\begin{aligned} \det K_1 &= 8 - 3 = 5 && \gcd(5, 26) = 1 \to \text{valid} \\ \det K_2 &= 6 - 4 = 2 && \gcd(2, 26) = 2 \to \text{invalid (even)} \\ \det K_3 &= 7 - 6 = 1 && \gcd(1, 26) = 1 \to \text{valid} \end{aligned}

Exercise 3: Inverse key by formula

Find the inverse mod 26 of K1=[2314]K_1 = \begin{bmatrix} 2 & 3 \\ 1 & 4 \end{bmatrix}.

Answer

K1−1≡[615516](mod26)K_1^{-1} \equiv \begin{bmatrix} 6 & 15 \\ 5 & 16 \end{bmatrix} \pmod{26}.

Solution
det⁡=5,and 5⋅21=105=4⋅26+1, so 5−1≡21adj⁡=[4−3−12]K−1≡21⋅[4−3−12]=[84−63−2142]≡[615516]\begin{aligned} \det &= 5, \quad \text{and } 5 \cdot 21 = 105 = 4 \cdot 26 + 1, \text{ so } 5^{-1} \equiv 21 \\ \operatorname{adj} &= \begin{bmatrix} 4 & -3 \\ -1 & 2 \end{bmatrix} \\ K^{-1} &\equiv 21 \cdot \begin{bmatrix} 4 & -3 \\ -1 & 2 \end{bmatrix} = \begin{bmatrix} 84 & -63 \\ -21 & 42 \end{bmatrix} \equiv \begin{bmatrix} 6 & 15 \\ 5 & 16 \end{bmatrix} \end{aligned}

Check with code:

python · try it yourself
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 P=[711411]P = \begin{bmatrix} 7 & 11 \\ 4 & 11 \end{bmatrix} (det⁡P=33≡7\det P = 33 \equiv 7, coprime to 26), so K=C⋅P−1 mod 26K = C \cdot P^{-1} \bmod 26.

python · try it yourself
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 KK usable for the Hill cipher mod 26?

  1. When det⁡K≠0\det K \ne 0
  2. When det⁡K\det K is coprime to 26
  3. When KK is symmetric
  4. When all entries are below 13

How many known plaintext/ciphertext blocks are typically enough to recover a 3×3 Hill key?

  1. 3
  2. 1
  3. 9
  4. 26

What do modern ciphers like AES add that the Hill cipher lacks?

  1. Bigger matrices only
  2. Longer alphabets
  3. Matrices modulo a prime
  4. Non-linear S-boxes, so no linear equation recovers the key