hill cipher with code examples

The Hill cipher is a classic example of a polygraphic substitution cipher, which seeks to enhance the security of encryption by considering letter pairs or groups rather than simply individual letters. Hill cipher has its basis in linear algebra and requires matrix arithmetic to encrypt and decrypt messages.

The basics of Hill cipher involve a key matrix of size n x n, where n is the size of the blocks of plaintext that are being encrypted. The message vector of size n x 1 is multiplied by the key matrix to produce a ciphertext vector of size n x 1.

In order to make the Hill cipher secure, the key matrix must be chosen in such a way that it is invertible, meaning that there exists another matrix called the inverse matrix that can be multiplied by the key matrix to give the identity matrix.

Let’s consider an example message to understand the working of the Hill cipher. Suppose our message is “SANDY”, with block size n of 2. So our message vector is [S, A, N, D, Y] and we can represent it as a matrix of size 2 x 3:

[S A N]
[D Y ]

Now suppose we have a key matrix of the same size:

[1 2]
[3 5]

To encrypt our message, we calculate the product of the message matrix and the key matrix:

[S A N] [1 2] [S+3A+N]
[D Y ] [3 5] [D+3Y]

Our ciphertext matrix is [S+3A+N, D+3Y]. So our encrypted message is “EQTOA”.

To decrypt the message, we must first find the inverse of the key matrix:

[1 2] [ 5 -2] [ 1 0]
[3 5] [-3 1] [ 0 1]

Now, using the inverse matrix and the ciphertext matrix, we can calculate the plaintext matrix as follows:

[S+3A+N, D+3Y] [ 5 -2] [S A N]
[-3 1] [D Y ]

Our plaintext matrix is [S, A, N, D, Y], which is the original message.

The Hill cipher is a great example of how mathematical concepts can be used for encryption in modern cryptography. Its security relies on the difficulty of determining the inverse key matrix and its strength is increased with increasing size of the key matrix and block size.

Code Example in Python:

Let's consider an example implementation of the Hill cipher in Python.

import numpy as np

def encrypt(message, key):
    # Prepare the message vector
    message = message.upper().replace(" ", "").replace(",", "")
    n = len(key)
    message += "X"*(n - len(message)%n)
    message_vec = [ord(c) - 65 for c in message]
    message_matrix = np.reshape(message_vec, (-1, n))
    # Prepare the key matrix
    key_vec = [ord(c) - 65 for c in key.upper()]
    key_matrix = np.reshape(key_vec, (n, n))
    # Encrypt the message
    ciphertext_matrix = np.mod(np.dot(message_matrix, key_matrix), 26)
    ciphertext_vec = np.reshape(ciphertext_matrix, (-1,))
    return ''.join([chr(c + 65) for c in ciphertext_vec])

def decrypt(ciphertext, key):
    # Prepare the ciphertext vector
    n = len(key)
    ciphertext_vec = [ord(c) - 65 for c in ciphertext.upper()]
    ciphertext_matrix = np.reshape(ciphertext_vec, (-1, n))
    # Prepare the key matrix
    key_vec = [ord(c) - 65 for c in key.upper()]
    key_matrix = np.reshape(key_vec, (n, n))

    # Find the inverse key matrix
    det = int(round(np.linalg.det(key_matrix)))
    inv_det = 0
    for i in range(26):
        if (i*det) % 26 == 1:
            inv_det = i
    inv_key_matrix = np.mod(inv_det*np.round(np.linalg.inv(key_matrix)*det), 26)
    # Decrypt the ciphertext
    plaintext_matrix = np.mod(np.dot(ciphertext_matrix, inv_key_matrix), 26)
    plaintext_vec = np.reshape(plaintext_matrix, (-1,))
    return ''.join([chr(c + 65) for c in plaintext_vec]).replace("X", "")

The function encrypt takes a plain message and a key as input and returns the corresponding ciphertext. The function decrypt takes a ciphertext and the original key used to encrypt the message and returns the plaintext. Note that the message must be in blocks of size n for encryption, so we add an "X" character at the end if necessary to have a complete block. The ciphertext is also returned with spaces replaced by "X" characters.


The Hill cipher is a classical encryption algorithm that has found its practical application in various fields of information security. While it is considered to be relatively weak compared to modern encryption standards, it is still a good example of how mathematical concepts can be used to provide cryptographic security.

let me elaborate more on the previously discussed topics:

  1. Polygraphic substitution cipher:

Polygraphic substitution ciphers are encryption methods that substitute a group of two or more letters at a time for another set of letters. They are considered more secure than monoalphabetic ciphers, which replace individual letters uniformly. Examples of polygraphic substition ciphers include Playfair cipher, Vigenere cipher, and Hill cipher.

Polygraphic substitution ciphers can be further classified into two types: columnar transposition ciphers and polyalphabetic ciphers. Columnar transposition ciphers involve rearranging the plaintext letters, while polyalphabetic ciphers use multiple alphabets to substitute letters.

  1. Linear Algebra:

Linear algebra is a branch of mathematics that studies the properties of linear equations, linear transformations, and vector spaces. It encompasses several concepts, including matrices, vectors, determinants, eigenvalues, and eigenvectors.

In cryptography, linear algebra is widely used in designing and implementing encryption algorithms. It helps in transforming plaintext into ciphertext through vector and matrix multiplication, and then reversing the process while decryption.

  1. Matrix Arithmetic:

Matrix arithmetic is a mathematical operation that involves the manipulation of matrices. It is a fundamental concept in linear algebra and is essential in many mathematical fields, including physics, engineering, economics, and finance.

Matrix arithmetic is also significant in cryptography, particularly in encryption and decryption algorithms such as the Hill cipher. Matrices are used to transform plaintext into ciphertext and vice versa by multiplying with a key matrix that contains the secret key.

The Hill cipher, as discussed earlier, relies on matrix arithmetic and linear algebra concepts to encrypt and decrypt messages. It is one of the few classical ciphers that are considered to be secure for small key sizes and can still be used for encryption in practical applications.

Popular questions

Sure, here are 5 questions and their answers regarding Hill Cipher with code examples:

  1. What is the Hill Cipher?

The Hill Cipher is a polygraphic substitution cipher that uses matrix arithmetic and linear algebra concepts to encrypt and decrypt messages. It involves a key matrix of size nxn, where n is the block size of the plaintext messages being encrypted. The message is represented as a matrix, which is multiplied by the key matrix to produce the ciphertext.

  1. How does the Hill Cipher achieve confidentiality?

The Hill Cipher achieves confidentiality by transforming the plaintext into ciphertext through matrix multiplication. The key matrix is kept secret and is used to encrypt and decrypt messages. Without the knowledge of the key matrix, an attacker cannot decipher the ciphertext and obtain the plaintext message.

  1. What is the role of linear algebra in the Hill Cipher?

Linear algebra plays a significant role in the Hill Cipher, as it involves several matrix operations, including multiplication, inverse, and determinant. The key matrix must be invertible to ensure the encryption and decryption process works correctly. The inverse matrix of the key matrix is used to decrypt the ciphertext and obtain the plaintext message.

  1. What is the purpose of adding "X" characters in the message during encryption?

The Hill Cipher requires the message to be in blocks of size nxn, where n is the block size. If the message is not in multiples of n, "X" characters are added at the end to form a complete block. This process ensures that the message is of the correct size for the matrix operations involved in encryption.

  1. What is the importance of finding the inverse key matrix in the Hill Cipher?

The inverse key matrix is essential in the Hill Cipher, as it is used to decrypt the ciphertext and obtain the original plaintext message. The inverse matrix is obtained by finding the determinant and then using modular arithmetic to compute its inverse. The inverse key matrix is required to reverse the matrix multiplication operation done during encryption. Without an inverse key matrix, it is impossible to decrypt the ciphertext and obtain the plaintext message.



As a seasoned software engineer, I bring over 7 years of experience in designing, developing, and supporting Payment Technology, Enterprise Cloud applications, and Web technologies. My versatile skill set allows me to adapt quickly to new technologies and environments, ensuring that I meet client requirements with efficiency and precision. I am passionate about leveraging technology to create a positive impact on the world around us. I believe in exploring and implementing innovative solutions that can enhance user experiences and simplify complex systems. In my previous roles, I have gained expertise in various areas of software development, including application design, coding, testing, and deployment. I am skilled in various programming languages such as Java, Python, and JavaScript and have experience working with various databases such as MySQL, MongoDB, and Oracle.
Posts created 3251

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top