Hill Cipher Encoder/Decoder

Enter text and a 2×2 key matrix to encode or decode with the Hill cipher.

How it is calculated

The tool encodes letters in pairs using a 2×2 key matrix [a b; c d] with A=0 to Z=25. Each pair (x, y) becomes (a·x + b·y) mod 26 and (c·x + d·y) mod 26. The text is made upper case and everything that is not A to Z is dropped (spaces, digits, punctuation and accented letters). An odd number of letters gets an X added at the end. Decoding uses the inverse key, det⁻¹ × [d −b; −c a] mod 26, where det = ad − bc mod 26. The key only works if det has an inverse mod 26, meaning det is odd and not a multiple of 13; otherwise the tool returns nothing. The determinant is displayed with the result.

Worked example

Encode HELP with key a=3, b=3, c=2, d=5. The determinant is 3·5 − 3·2 = 9, which is invertible mod 26. Pair 1 is H=7, E=4: (3·7 + 3·4) mod 26 = 33 mod 26 = 7 = H, and (2·7 + 5·4) mod 26 = 34 mod 26 = 8 = I. Pair 2 is L=11, P=15: (33 + 45) mod 26 = 0 = A, and (22 + 75) mod 26 = 19 = T. The ciphertext is HIAT, with determinant 9. Switching to decode mode with the same key returns HELP.

Try this example →

Common mistakes

  • Choosing a key with an even determinant or one divisible by 13 (for example 2, 4, 1, 2, which gives det 0); there is no inverse, so the tool returns nothing.
  • Expecting spaces, digits and punctuation to survive; they are removed, so decoding gives back letters only, with no word breaks.
  • Forgetting that an odd-length message gets a trailing X when encrypted, so the decoded text may end in an extra X.
  • Decoding with a different key than was used to encode, or leaving the mode on encode when you want the plaintext back.
  • Reading the key matrix by columns instead of rows: the tool multiplies row (a b) by the pair for the first letter, and row (c d) for the second.

About this calculator

Invented by Lester Hill in 1929, the Hill cipher is a classical polygraphic substitution cipher that encrypts letters in blocks rather than one at a time using linear algebra: each pair of letters is mapped to a 2×1 number vector (A=0…Z=25), multiplied by a 2×2 key matrix, and reduced modulo 26 to produce the ciphertext pair. Decryption reverses the process using the key matrix's modular inverse, which only exists if the matrix's determinant is coprime with 26.

This tool encrypts or decrypts text with a Hill cipher given a 2×2 key matrix, handling the modular arithmetic and matrix inversion automatically. Cryptography students and computer science instructors use it to see how matrix multiplication produces diffusion across letter pairs, and to check by-hand homework against a working reference implementation.

Was this helpful?

You can pick up to 3 reactions.

Comments

  • Be the first to comment.

Popular calculators

All Calculators