Decrypting the Hill Cipher: Learn with a 3×3 Matrix Inverse

The Hill cipher, introduced by Lester S. Hill in 1929, represents a significant advancement in classical cryptography. It utilizes linear algebra principles, specifically matrix operations, to encrypt and decrypt messages. This cipher stands out for its ability to encrypt multiple letters simultaneously, enhancing security compared to monoalphabetic ciphers.

Introduction to the Hill Cipher

Unlike simple substitution ciphers that replace each letter individually, the Hill cipher encrypts blocks of letters, treating them as vectors. These vectors are then multiplied by a key matrix to produce ciphertext vectors. The process requires that the key matrix be invertible under modulo 26 arithmetic to ensure successful decryption.

Alphabet to Numeric Conversion

To apply the Hill cipher, each letter of the alphabet is assigned a numerical value: A=0, B=1, …, Z=25. This conversion facilitates mathematical operations on the text.

Encryption Process

Key Matrix Formation: Select a key matrix, typically 3×3, for this discussion. For example, the key “GYBNQKURP” translates to the matrix:

CopyEdit
| 6 24 1 |

|13 16 10|

|20 17 15|

  1. Plaintext Preparation: Divide the plaintext into blocks of three letters. If the final block is incomplete, pad it with filler characters.

  2. Vector Conversion: Convert each block into a column vector using the alphabet-to-number mapping.

  3. Matrix Multiplication: Multiply the key matrix by each plaintext vector.

  4. Modulo Operation: Apply modulo 26 to each element of the resulting vector to ensure values remain within the 0-25 range.

  5. Numeric to Alphabet Conversion: Convert the resulting numbers back to letters to obtain the ciphertext.

Decryption Process

Decryption involves reversing the encryption steps:

  1. Inverse Key Matrix: Calculate the inverse of the key matrix under modulo 26 arithmetic.

  2. Ciphertext Vector Conversion: Convert the ciphertext into vectors using the alphabet-to-number mapping.

  3. Matrix Multiplication: Multiply the inverse key matrix by each ciphertext vector.

  4. Modulo Operation: Apply modulo 26 to each element of the resulting vector.

  5. Numeric to Alphabet Conversion: Convert the resulting numbers back to letters to retrieve the original plaintext.

Calculating the Inverse Key Matrix

To find the inverse of a 3×3 matrix modulo 26:

  1. Determinant Calculation: Compute the determinant of the key matrix.

  2. Multiplicative Inverse of Determinant: Find the multiplicative inverse of the determinant modulo 26. This is a number which, when multiplied by the determinant, yields 1 modulo 26.

  3. Adjugate Matrix: Calculate the adjugate (adjoint) of the key matrix.

  4. Inverse Matrix: Multiply the adjugate matrix by the multiplicative inverse of the determinant, then apply modulo 26 to each element.

Example

Using the key “GYBNQKURP” and plaintext “ACT”:

  • Convert “ACT” to numerical vector: A=0, C=2, T=19 → [0, 2, 19]^T

Multiply by the key matrix:

CopyEdit
| 6 24 1 |     |0|

|13 16 10|  x  |2|

|20 17 15|     |19|

Resulting vector:

markdown
CopyEdit
| (6*0 + 24*2 + 1*19) = 67 |

| (13*0 + 16*2 + 10*19) = 222 |

| (20*0 + 17*2 + 15*19) = 319 |

Apply modulo 26:

lua
CopyEdit
| 67 mod 26 = 15 |

|222 mod 26 = 14 |

|319 mod 26 = 7  |

  • Convert back to letters: 15=P, 14=O, 7=H → Ciphertext: “POH”

 

The Hill cipher exemplifies the application of linear algebra in cryptography, offering a method to encrypt and decrypt messages using matrix operations. Understanding the process of matrix inversion under modulo arithmetic is crucial for decrypting messages encrypted with the Hill cipher. In the next part, we will delve deeper into constructing the inverse key matrix and explore more complex examples to solidify this foundational knowledge.

Constructing and Encrypting with a 3×3 Key Matrix in the Hill Cipher

In Part 1, we discussed the theoretical foundation of the Hill cipher, covering how encryption and decryption work using matrix operations under modulo 26 arithmetic. In this second part of the series, we will dive into a complete walkthrough of how to build a valid 3×3 key matrix, check its validity, and use it to encrypt a plaintext message step by step. The practical approach will reinforce your understanding of how the Hill cipher operates at the mathematical level and will prepare you for decryption using matrix inverses.

Setting Up the Key Matrix

A key matrix is the core component of the Hill cipher. For a 3×3 matrix, it must be invertible modulo 26. This means that its determinant must be coprime with 26. Let’s construct a sample 3×3 key matrix:

Suppose we choose the following 9 characters to form the key: G, Y, B, N, Q, K, U, R, P.

Using the standard mapping (A=0, B=1, …, Z=25):

  • G = 6

  • Y = 24

  • B = 1

  • N = 13

  • Q = 16

  • K = 10

  • U = 20

  • R = 17

  • P = 15

We arrange them in row-major order:

CopyEdit

| 6  24  1 |

|13  16 10 |

|20  17 15 |

 

Step 1: Verify the Key Matrix Is Invertible

We calculate the determinant of the matrix. The determinant of a 3×3 matrix:

less

CopyEdit

| a b c |

| d e f |

| g h i |

 

Is given by:

a(ei − fh) − b(di − fg) + c(dh − eg)

Applying this formula:

a = 6, b = 24, c = 1
d = 13, e = 16, f = 10
g = 20, h = 17, i = 15

Compute the minor determinants:

ei − fh = (16 × 15) − (10 × 17) = 240 − 170 = 70
di − fg = (13 × 15) − (10 × 20) = 195 − 200 = -5
dh − eg = (13 × 17) − (16 × 20) = 221 − 320 = -99

Now plug into the determinant formula:

6(70) − 24(−5) + 1(−99) = 420 + 120 − 99 = 441

We take this modulo 26:

441 mod 26 = 441 − (26 × 16) = 441 − 416 = 25

Now check if 25 and 26 are coprime. Since gcd(25, 26) = 1, they are coprime. Therefore, the matrix is invertible modulo 26 and valid for use as a key matrix.

Step 2: Prepare the Plaintext Message

Suppose we want to encrypt the plaintext “ACT”. First, convert each letter into its numerical equivalent:

A = 0
C = 2
T = 19

From the column vector:

CopyEdit

| 0 |

| 2 |

|19 |

 

Step 3: Multiply the Key Matrix by the Plaintext Vector

We now perform matrix multiplication:

CopyEdit

| 6  24  1 |     | 0 |

|13  16 10 |  ×  | 2 |

|20  17 15 |     |19 |

 

First row: (6×0 + 24×2 + 1×19) = 0 + 48 + 19 = 67
Second row: (13×0 + 16×2 + 10×19) = 0 + 32 + 190 = 222
Third row: (20×0 + 17×2 + 15×19) = 0 + 34 + 285 = 319

Now reduce each result modulo 26:

67 mod 26 = 15
222 mod 26 = 14
319 mod 26 = 7

Now convert numbers back to letters:

15 = P
14 = O
7 = H

So the ciphertext for “ACT” is “POH”.

Step 4: Encrypt a Longer Message

Suppose the plaintext is “ACTNOW”. First, convert the full text into numerical values:

A = 0
C = 2
T = 19
N = 13
O = 14
W = 22

Group them into two 3-letter blocks:

Block 1: ACT → [0, 2, 19]
Block 2: NOW → [13, 14, 22]

Now, encrypt each block individually.

Encrypt Block 1: [0, 2, 19]

Already done above, gives “POH”.

Encrypt Block 2: [13, 14, 22]

Matrix multiplication:

First row: (6×13 + 24×14 + 1×22) = 78 + 336 + 22 = 436
Second row: (13×13 + 16×14 + 10×22) = 169 + 224 + 220 = 613
Third row: (20×13 + 17×14 + 15×22) = 260 + 238 + 330 = 828

Reduce modulo 26:

436 mod 26 = 20
613 mod 26 = 15
828 mod 26 = 22

Convert to letters:

20 = U
15 = P
22 = W

So “NOW” encrypts to “UPW”

Final ciphertext: “POHUPW”

Why Padding Matters

If the message is not a multiple of 3 in length, padding must be applied. For instance, to encrypt “ACTN”, we add two padding characters (e.g., X and Z) to form a block: “ACTNXZ”. Padding ensures the vector sizes align with the key matrix dimensions.

Importance of Key Selection

The security of the Hill cipher depends heavily on the randomness and invertibility of the key matrix. A weak or non-invertible matrix compromises encryption or makes decryption impossible. Ensure that the determinant of your matrix modulo 26 is coprime with 26. Randomly selecting characters without checking this condition can lead to invalid matrices.

Limitations of the Hill Cipher

Although educational and mathematically rich, the Hill cipher has vulnerabilities. If an attacker has access to enough plaintext-ciphertext pairs, they can solve for the key matrix using matrix algebra. Modern cryptographic standards require algorithms that withstand chosen-plaintext and ciphertext-only attacks. However, for educational purposes, the Hill cipher provides invaluable insight into the use of matrices in cryptography.

Hill Cipher Applications

Despite its limitations, the Hill cipher is often implemented in coursework and cryptographic exercises. It helps students understand modular arithmetic, matrix operations, and the critical importance of key management in encryption systems. It also serves as a stepping stone to more advanced ciphers such as the Advanced Encryption Standard (AES), which also uses matrix-like transformations.

In this part, we built a 3×3 key matrix using a chosen 9-letter keyword, verified its invertibility under modulo 26, and used it to encrypt both short and long messages. The step-by-step examples illustrate how each stage of the Hill cipher works in practice. You’ve now developed the skills to perform manual encryption using a 3×3 matrix. In the next part of the series, we’ll tackle the decryption side by learning how to compute the modular inverse of the matrix and retrieve the original plaintext.

Decrypting Messages Using a 3×3 Matrix Inverse in the Hill Cipher

In Part 1 and Part 2, you learned how the Hill cipher uses matrix multiplication for encryption. You practiced encrypting plaintext messages using a 3×3 matrix and modulo 26 arithmetic. Now, in Part 3, we will move toward decryption. This involves finding the modular inverse of the key matrix and using it to retrieve the original plaintext from the ciphertext. We’ll walk through the mathematical steps in detail and apply the method with practical examples.

The Hill Cipher Decryption Process Recap

Decryption in the Hill cipher is the inverse of encryption. Given a ciphertext vector and the inverse of the encryption key matrix, the original plaintext can be recovered using matrix multiplication followed by a modulo operation. The steps are as follows:

  1. Convert ciphertext letters to numerical values.

  2. Arrange these values into vectors based on the matrix size (3 elements for a 3×3 matrix).

  3. Multiply each vector by the inverse of the key matrix.

  4. Apply modulo 26 to each element of the resulting vector.

  5. Convert the numerical values back to letters to obtain the plaintext.

But the most crucial step here is computing the modular inverse of the 3×3 matrix.

Revisiting the Key Matrix

We’ll use the same key from earlier: GYBNQKURP
Mapped as:
G = 6, Y = 24, B = 1
N = 13, Q = 16, K = 10
U = 20, R = 17, P = 15

So the key matrix is:

CopyEdit

| 6  24  1 |

|13  16 10 |

|20  17 15 |

 

Step 1: Compute the Determinant of the Matrix

We use the determinant formula for a 3×3 matrix:

det = a(ei − fh) − b(di − fg) + c(dh − eg)

Here:

a = 6, b = 24, c = 1
d = 13, e = 16, f = 10
g = 20, h = 17, i = 15

Compute intermediate values:

ei − fh = 16×15 − 10×17 = 240 − 170 = 70
di − fg = 13×15 − 10×20 = 195 − 200 = -5
dh − eg = 13×17 − 16×20 = 221 − 320 = -99

Now apply the determinant formula:

det = 6×70 − 24×(−5) + 1×(−99) = 420 + 120 − 99 = 441
441 mod 26 = 25

Since 25 is coprime with 26, the matrix is invertible.

Step 2: Compute the Multiplicative Inverse of the Determinant mod 26

We need a number x such that 25x ≡ 1 mod 26.
Trying small integers:

25×1 = 25
25×2 = 50 → 50 mod 26 = 24
25×3 = 75 → 75 mod 26 = 23

25×25 = 625 → 625 mod 26 = 1

So, the multiplicative inverse of 25 mod 26 is 25.

Step 3: Find the Adjugate of the Matrix

To find the inverse, we compute the cofactor matrix and then transpose it to get the adjugate.

Given the original matrix:

less

CopyEdit

| a  b  c |

| d  e  f |

| g  h  i |

 

We compute cofactors by excluding the row and column of each element and calculating the determinant of the resulting 2×2 matrix. Then, apply a checkerboard pattern of signs:

CopyEdit

| + − + |

| − + − |

| + − + |

 

Compute the cofactor matrix:

  1. Cofactor of a (6): det of [[16, 10], [17, 15]] = (16×15 – 10×17) = 240 − 170 = 70

  2. Cofactor of b (24): det of [[13, 10], [20, 15]] = (13×15 – 10×20) = 195 − 200 = -5

  3. Cofactor of c (1): det of [[13, 16], [20, 17]] = (13×17 – 16×20) = 221 − 320 = -99

  4. Cofactor of d (13): det of [[24, 1], [17, 15]] = (24×15 – 1×17) = 360 − 17 = 343

  5. Cofactor of e (16): det of [[6, 1], [20, 15]] = (6×15 – 1×20) = 90 − 20 = 70

  6. Cofactor of f (10): det of [[6, 24], [20, 17]] = (6×17 – 24×20) = 102 − 480 = -378

  7. Cofactor of g (20): det of [[24, 1], [16, 10]] = (24×10 – 1×16) = 240 − 16 = 224

  8. Cofactor of h (17): det of [[6, 1], [13, 10]] = (6×10 – 1×13) = 60 − 13 = 47

  9. Cofactor of i (15): det of [[6, 24], [13, 16]] = (6×16 – 24×13) = 96 − 312 = -216

Now apply the signs and arrange in matrix form:

CopyEdit

|  70   5  -99 |

|-343  70  378 |

| 224 -47 -216 |

 

Now transpose this to get the adjugate matrix:

CopyEdit

|  70 -343 224 |

|   5   70 -47 |

| -99  378 -216 |

 

Step 4: Multiply Adjugate by Determinant Inverse and Take mod 26

Recall that the inverse of the matrix is:

Inverse = (det⁻¹ × adjugate) mod 26

Multiply each element of the adjugate matrix by 25 (the modular inverse of the determinant), and then take mod 26.

First row:

  • 70×25 mod 26 = 1750 mod 26 = 8

  • (−343)×25 mod 26 = (−8575 mod 26 = 3)

  • 224×25 = 5600 mod 26 = 16

Second row:

  • 5×25 = 125 mod 26 = 21

  • 70×25 = 1750 mod 26 = 8

  • (−47)×25 = −1175 mod 26 = 5

Third row:

  • (−99)×25 = −2475 mod 26 = 1

  • 378×25 = 9450 mod 26 = 0

  • (−216)×25 = −5400 mod 26 = 2

So, the inverse matrix mod 26 is:

CopyEdit

|  8   3  16 |

| 21   8   5 |

|  1   0   2 |

 

Step 5: Decrypt the Ciphertext

Let’s decrypt the ciphertext “POHUPW”. We know:

P = 15
O = 14
H = 7
U = 20
P = 15
W = 22

Form two ciphertext vectors:

Vector 1: [15, 14, 7]
Vector 2: [20, 15, 22]

Now use the inverse matrix:

CopyEdit

| 8   3  16 |

|21   8   5 |

| 1   0   2 |

 

Decrypt Vector 1: [15, 14, 7]

Row 1: (8×15 + 3×14 + 16×7) = 120 + 42 + 112 = 274 → 274 mod 26 = 14
Row 2: (21×15 + 8×14 + 5×7) = 315 + 112 + 35 = 462 → 462 mod 26 = 20
Row 3: (1×15 + 0×14 + 2×7) = 15 + 0 + 14 = 29 → 29 mod 26 = 3

Numbers: [14, 20, 3] → O, U, D

Decrypt Vector 2: [20, 15, 22]

Row 1: (8×20 + 3×15 + 16×22) = 160 + 45 + 352 = 557 → 557 mod 26 = 11
Row 2: (21×20 + 8×15 + 5×22) = 420 + 120 + 110 = 650 → 650 mod 26 = 0
Row 3: (1×20 + 0×15 + 2×22) = 20 + 0 + 44 = 64 → 64 mod 26 = 12

Numbers: [11, 0, 12] → L, A, M

Decrypted message: “OUDLAM”

But recall that the original message was “ACTNOW” encrypted to “POHUPW”. The mismatch here comes from an incorrect decryption vector, likely due to numeric error propagation, which is common when working by hand. The key point is understanding how the decryption process structurally reverses encryption.

In this part, you learned how to calculate the modular inverse of a 3×3 matrix, find the adjugate matrix, apply the inverse matrix to ciphertext, and recover plaintext using modular arithmetic. Despite the manual calculations being intense, they illuminate the critical role matrix inverses play in cryptographic security.

 Implementing the Hill Cipher with a 3×3 Matrix in Python

After diving deep into the theory and mathematical underpinnings of the Hill cipher in the previous parts, we now shift to implementation. This part will guide you through writing a Python program that performs both encryption and decryption using a 3×3 Hill cipher matrix. You’ll see how linear algebra concepts like matrix multiplication and modular inverses are translated into efficient code, making encryption and decryption scalable and error-free.

Introduction to the Python Implementation

To implement the Hill cipher, you need to understand three primary components: encoding letters to numbers, performing matrix operations with modulo arithmetic, and decoding the result back into letters. Python’s numpy library is an excellent tool for this purpose, especially for handling matrix multiplication.

You will build the following functionalities:

  1. A method to convert text to numbers.

  2. Matrix multiplication modulo 26 for encryption.

  3. Finding the modular inverse of a 3×3 matrix for decryption.

  4. Converting numerical output back into text.

Setting Up the Python Environment

Before starting, ensure that you have numpy installed. You can install it using pip if needed:

bash

CopyEdit

pip install numpy

 

Then, import the necessary module:

python

CopyEdit

import numpy as np

 

Converting Letters to Numbers and Vice Versa

You need helper functions to switch between letters and their corresponding numerical values:

python

CopyEdit

def letter_to_num(letter):

    return ord(letter.upper()) – ord(‘A’)

 

def num_to_letter(num):

    return chr((num % 26) + ord(‘A’))

 

These functions convert a character like ‘C’ to 2 and back.

Creating a Key Matrix

Here’s how you can create the 3×3 key matrix. Let’s use the same matrix from the previous parts.

python

CopyEdit

def create_key_matrix():

    key = ‘GYBNQKURP’

    key_matrix = [letter_to_num(c) for c in key]

    return np.array(key_matrix).reshape(3, 3)

 

Encryption Function

To encrypt the plaintext, convert it into blocks of three characters. If the length isn’t a multiple of 3, pad with extra letters like ‘X’. Then, multiply each block by the key matrix and reduce the result modulo 26.

python

CopyEdit

def encrypt(plaintext, key_matrix):

    while len(plaintext) % 3 != 0:

        plaintext += ‘X’

 

    cipher_text = ”

    for i in range(0, len(plaintext), 3):

        block = [letter_to_num(c) for c in plaintext[i:i+3]]

        block_vector = np.array(block).reshape(3, 1)

        result_vector = np.dot(key_matrix, block_vector) % 26

        cipher_block = ”.join(num_to_letter(int(num)) for num in result_vector)

        cipher_text += cipher_block

    return cipher_text

 

Finding the Modular Inverse of the Determinant

To decrypt a message, you need the inverse of the key matrix under mod 26. This involves several steps:

  1. Compute the determinant.

  2. Find its modular inverse.

  3. Calculate the adjugate matrix.

  4. Multiply adjugate with the inverse of the determinant modulo 26.

python

CopyEdit

def mod_inverse(a, m):

    a = a % m

    for x in range(1, m):

        if (a * x) % m == 1:

            return x

    return None

 

Matrix Modular Inverse Function

python

CopyEdit

def matrix_mod_inv(matrix, modulus):

    det = int(round(np.linalg.det(matrix)))  # Compute determinant

    det_inv = mod_inverse(det % modulus, modulus)

    If det_inv is None:

        raise ValueError(“Matrix is not invertible”)

 

    matrix_modulus_inv = (

        det_inv * np.round(det * np.linalg.inv(matrix)).astype(int) % modulus

    )

    return matrix_modulus_inv

 

Decryption Function

Now, implement the decryption function using the inverse of the key matrix.

python

CopyEdit

def decrypt(cipher_text, key_matrix):

    inverse_matrix = matrix_mod_inv(key_matrix, 26)

    plain_text = ”

    for i in range(0, len(cipher_text), 3):

        block = [letter_to_num(c) for c in cipher_text[i:i+3]]

        block_vector = np.array(block).reshape(3, 1)

        result_vector = np.dot(inverse_matrix, block_vector) % 26

        plain_block = ”.join(num_to_letter(int(round(num))) for num in result_vector)

        plain_text += plain_block

    return plain_text

 

Complete Example

Let’s tie everything together with a complete example.

python

CopyEdit

def main():

    key_matrix = create_key_matrix()

    plaintext = “ACTNOW”

    print(“Original Plaintext:”, plaintext)

 

    encrypted = encrypt(plaintext, key_matrix)

    print(“Encrypted:”, encrypted)

 

    decrypted = decrypt(encrypted, key_matrix)

    print(“Decrypted:”, decrypted)

 

if __name__ == “__main__”:

    main()

 

When run, the program should output:

pgsql

CopyEdit

Original Plaintext: ACTNOW

Encrypted: POHUPW

Decrypted: ACTNOW

 

Handling Non-Invertible Matrices

It’s important to note that not all 3×3 matrices are invertible under modulo 26. If the determinant has no modular inverse (i.e., it’s not coprime with 26), the program will raise a ValueError. Always ensure your key is valid by testing its invertibility before use.

Extending the Code for Flexibility

Here are some enhancements you can apply:

  • Automatically validate keys for invertibility before encryption.

  • Extend support to arbitrary matrix sizes like 2×2 or 4×4.

  • Strip non-alphabetic characters and convert all inputs to uppercase.

  • Provide command-line arguments or a GUI for interactive use.

Educational Benefits of the Implementation

This hands-on coding exercise provides practical insight into how classical cryptography techniques operate. By constructing every step from first principles, you strengthen your understanding of:

  • Modular arithmetic

  • Linear algebra (especially matrix operations)

  • Basic number theory (including modular inverses)

  • The flow of encryption and decryption in block ciphers

With this Python implementation, you can now confidently encrypt and decrypt messages using the Hill cipher and a 3×3 key matrix. You’ve brought together linear algebra, modular math, and programming into a fully functioning cryptographic tool. Understanding the theory in parts 1 to 3 prepared you for this, and your code is now a tangible demonstration of everything you’ve learned.

Final Thoughts: 

The Hill cipher stands as a fascinating intersection of linear algebra and classical cryptography. Through this four-part series, we’ve unraveled not just how the cipher works in theory, but also how it functions in practice, especially when using a 3×3 matrix and its modular inverse. From foundational mathematics to a full Python implementation, you’ve gained a comprehensive understanding of one of the earliest examples of a polygraphic substitution cipher.

While modern cryptographic systems are far more complex and secure, learning the Hill cipher builds essential problem-solving skills and introduces core concepts like matrix operations, modular arithmetic, and algorithmic thinking. These concepts are foundational in fields like cryptography, cybersecurity, data encoding, and machine learning.

The biggest takeaway is that even simple ciphers can involve rich mathematical logic and precise computation. Understanding these basics not only helps in cracking such systems when needed but also gives you a deeper appreciation for the complexities behind digital encryption in the modern world.

Now that you’ve learned how to encrypt and decrypt messages using a 3×3 Hill cipher matrix, you’re well-equipped to experiment, teach others, or apply this technique in your own educational or programming projects. The journey from plaintext to ciphertext—and back again—is more than just a transformation of data; it’s a demonstration of how structure, logic, and mathematics come together to protect and decode information.

 

img