Hill Cipher (2×2)

Matrix-based classical cipher with a 2×2 key matrix mod 26.

Open tool

Overview

The Hill cipher tool encrypts and decrypts text using a 2×2 matrix key over the integers modulo 26. Enter a key matrix and a message; the tool returns the substituted text, working in pairs of letters rather than one at a time.

It is a teaching tool for linear-algebra-in-cryptography courses, a puzzle aid for cryptograms that use matrix keys, and a quick reference when you are working through Lester Hill's 1929 cipher by hand. The Hill cipher is famous for being the first practical cipher to operate on more than three symbols at a time.

How it works

A 2×2 Hill cipher treats two consecutive plaintext letters as a column vector P = (p1, p2)^T, where A=0, B=1, ..., Z=25. The key is a 2×2 matrix K over Z/26Z. The ciphertext vector is C = K·P (mod 26). Decryption multiplies by K^-1 (mod 26), which exists only when det(K) is coprime with 26 (so not divisible by 2 or 13). The plaintext is padded — usually with X — when its length is odd. Non-letter characters are typically stripped before encryption and reinserted around the output, depending on the implementation.

Examples

Key matrix: [[5, 17], [8, 3]]
Plaintext:  HELP
Pairs:      (H,E)=(7,4), (L,P)=(11,15)
Ciphertext: ZEBB
Key matrix: [[3, 3], [2, 5]]   (det = 9, gcd(9,26)=1 — invertible)
Plaintext:  HI
Ciphertext: KN
Key matrix: [[6, 24], [1, 13]]
Plaintext:  ATTACK
Ciphertext: POH... (paired columns)

FAQ

Why must det(K) be coprime to 26?

To invert K modulo 26 you need to invert det(K) modulo 26, which is only possible when gcd(det(K), 26) = 1. Since 26 = 2 × 13, the determinant must avoid factors of 2 and 13.

Is Hill secure?

No. A known-plaintext attack recovers the key in seconds — a few plaintext/ciphertext pairs are enough to solve for K directly. Hill is a historical and pedagogical cipher only.

How is the message padded?

If the plaintext length is odd, the last letter is paired with X (or another agreed filler). Some variants pad on the front; this tool pads on the back.

Can I use a 3×3 key?

This tool focuses on the canonical 2×2 case. Larger Hill ciphers exist (the math generalises to any invertible matrix mod 26) but are even less common in practice.

Try Hill Cipher (2×2)

An unhandled error has occurred. Reload ×