Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is represented by a number modulo 26. Often the simple scheme A = 0, B = 1, …, Z = 25 is used, but this is not an essential feature of the cipher. To encrypt a message, each block of n letters (considered as an n-component vector) is multiplied by an invertible n × n matrix, against modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.
The matrix used for encryption is the cipher key, and it should be chosen randomly from the set of invertible n × n matrices (modulo 26).
Input : Plaintext: ACT Key: GYBNQKURP Output : Ciphertext: POH
Input : Plaintext: GFG Key: HILLMAGIC Output : Ciphertext: SWK
We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which can be written as the nxn matrix:
The message ‘ACT’ is written as vector:
The enciphered vector is given as:
which corresponds to ciphertext of ‘POH’
To decrypt the message, we turn the ciphertext back into a vector, then simply multiply by the inverse matrix of the key matrix (IFKVIVVMI in letters).The inverse of the matrix used in the previous example is:
For the previous Ciphertext ‘POH’:
which gives us back ‘ACT’.
Assume that all the alphabets are in upper case.
Below is the implementation of the above idea for n=3.
In a similar way you can write the code for decrypting the encrypted message by following the steps explained above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Difference between Monoalphabetic Cipher and Polyalphabetic Cipher
- Introduction to Hill Climbing | Artificial Intelligence
- Caesar Cipher in Cryptography
- Vigenère Cipher
- XOR Cipher
- Rail Fence Cipher - Encryption and Decryption
- Implementation of Affine Cipher
- Columnar Transposition Cipher
- ROT13 cipher
- Implementing Atbash Cipher
- Baconian Cipher
- Keyword Cipher
- Null Cipher
- Latin alphabet cipher
- Polybius Square Cipher
- Transforming a Plain Text message to Cipher Text
- Playfair Cipher with Examples
- Vernam Cipher in Cryptography
- Bifid Cipher in Cryptography
- Substitution Cipher
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.