Hill Cipher
Nerd Cafe
The Hill Cipher is a polygraphic substitution cipher that uses linear algebra to encrypt and decrypt messages. It operates on blocks of text (usually in groups of 2 or 3 characters), treating each block as a vector of numbers, and applies matrix multiplication to perform the encryption.
Here’s a step-by-step guide to understanding and using the Hill Cipher with a practical example.
Step 1: Understand the Hill Cipher Matrix
The key in the Hill cipher is a square matrix (let's call it key matrix), usually of size 2×2 or 3×3. The matrix is used for both encryption and decryption, so it needs to be invertible (its determinant should not be 0).
For a 2×2 matrix: The matrix will look like this:
For a 3×3 matrix: The matrix will look like this:
Step 2: Choose a Key Matrix
For encryption, we need to choose a key matrix. Let's choose a 2×2 key matrix for simplicity.
Example key matrix 𝐾:
Step 3: Assign Numbers to the Letters
The alphabet is mapped to numbers:
Example: "HI" (which we want to encrypt):
So the plaintext "HI" is represented as the vector:
Step 4: Perform Matrix Multiplication
Now, the encryption process involves multiplying the key matrix 𝐾 by the plaintext vector 𝑃. The formula for encryption is:
Step 5: Take Modulo 26
To make sure the result fits into the range of 0 to 25 (the alphabet), we take the modulo 26 of each element.
37mod26=1115mod26=15
Thus, the encrypted vector is:
Step 6: Convert the Encrypted Numbers Back to Letters
Using the same alphabet-to-number mapping, we convert the numbers back to letters:
11 = L
15 = P
So the ciphertext corresponding to "HI" is "LP".
Step 7: Decryption (Optional)
The formula for the inverse of a 2x2 matrix is given by:
We first need to compute the determinant.
Since the determinant is 1, the inverse exists and we can proceed. Next, we apply the formula for the inverse:
Now, we simplify the matrix modulo 26:
So the inverse key matrix is:
The ciphertext "LP" corresponds to the following numerical values:
L → 11
P → 15
So, the ciphertext vector 𝐶 is:
Now, the decryption process involves multiplying the inverse key matrix 𝐾−1 by the ciphertext vector 𝐶. The formula for decryption is:
Let's perform the matrix multiplication:
and so we have:
So, the plaintext vector 𝑃 is:
Finally, we convert the numbers back to letters:
7 → H8 → I
Step 8: Python Code for Hill Cipher:
Sure! Below is a Python code implementation for the Hill Cipher encryption and decryption.
Output
Last updated