Hill Cipher

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

Free Hill cipher encoder and decoder using a 2×2 key matrix. Encrypts digraphs by matrix multiplication modulo 26 and decrypts with the modular matrix inverse, checking that the key determinant is invertible mod 26. Shows the inverse key. Runs entirely in your browser. It runs free in your browser on Gera Tools, with nothing uploaded.

Last updated Source: Gera Tools

How does the Hill cipher encrypt text?

Letters are mapped to numbers A=0 to Z=25 and grouped into pairs (digraphs). Each pair is treated as a column vector and multiplied by the 2×2 key matrix modulo 26, producing a new pair of numbers that map back to ciphertext letters.

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.