Hill Cipher

Polygraphic cipher that encrypts letter pairs with a 2×2 matrix multiplication mod 26.

Ad placeholder (leaderboard)

The Hill cipher, invented by Lester S. Hill in 1929, was the first practical cipher to encrypt more than one letter at a time using linear algebra. Instead of substituting single letters, it treats blocks of letters as vectors and multiplies them by a key matrix modulo 26. This tool implements the classic 2×2 version, which encrypts the message two letters at a time.

How it works

Each letter is converted to a number with A = 0, B = 1, … Z = 25. The plaintext is split into pairs of letters, and each pair is written as a column vector. To encrypt, the vector is multiplied by the 2×2 key matrix and every result is reduced modulo 26:

[ a b ] [ p1 ]   [ (a·p1 + b·p2) mod 26 ]
[ c d ] [ p2 ] = [ (c·p1 + d·p2) mod 26 ]

The two output numbers map back to ciphertext letters. To decrypt, the ciphertext vector is multiplied by the modular inverse of the key matrix. For a 2×2 matrix the inverse is the modular inverse of the determinant det = (a·d − b·c) mod 26 multiplied by the adjugate matrix [d, −b; −c, a]. This only exists when det is coprime with 26, so the tool checks that condition before encrypting.

Worked example

With key matrix [3 3; 2 5] the determinant is 3·5 − 3·2 = 9, and gcd(9, 26) = 1, so the key is valid. The plaintext pair HE becomes numbers (7, 4). Multiplying gives (3·7 + 3·4, 2·7 + 5·4) = (33, 34), which reduces mod 26 to (7, 8) — the ciphertext letters HI. Decryption multiplies by the inverse key to return (7, 4) and recover HE.

Notes and tips

Choose a key whose determinant is coprime with 26 — avoid even determinants and multiples of 13. Messages are upper-cased and non-letters are removed before encryption, and an X is appended if the letter count is odd so the last pair is complete. The Hill cipher is linear and therefore breakable with known plaintext; use it for learning, not for protecting secrets. All computation runs locally in your browser.

Ad placeholder (rectangle)