Hill Cipher
Another interesting multi letter cipher is the Hill cipher, developed by the mathematician Lester Hill in 1929.
THE HILL ALGORITHM
This encryption algorithm takes n successive plaintext letters and substitutes for them n ciphertext letters. The substitution is determined by linear equations in which each character is assigned a numerical value (a=0,b=1,…,z=25).
C=KP, where K is the key matrix and P is the plaintext vector
P=K−1C, where K−1 is the inverse of key matrix K in (mod26)
How the Hill Cipher WorksKey Matrix:
- Choose a key matrix
K
of size n×n (e.g., 2×2, 3×3). - The key matrix should be invertible modulo 26 (the number of letters in the English alphabet).
- Choose a key matrix
Plaintext Preparation:
- Convert the plaintext into vectors of size n.
- If the plaintext length is not a multiple of n, pad it with extra letters (e.g., 'X').
Encryption:
- Multiply the key matrix K by each plaintext vector, and take the result modulo 26 to get the ciphertext vector.
- Convert the resulting numbers back into letters.
Decryption:
- Calculate the inverse of the key matrix K−1 modulo 26.
- Multiply the inverse matrix by each ciphertext vector, and take the result modulo 26 to get the plaintext vector.
- Convert the resulting numbers back into letters.
Example
Let's encrypt the plaintext "HELP" using a 2×2 key matrix.
Step 1: Key Matrix
Choose the key matrix: K=[3325]
Step 2: Plaintext Preparation
Convert "HELP" into numbers: H=7, E=4, L=11, P=15
Since our key matrix is 2×2, divide the plaintext into pairs:
- (H, E) -> (7, 4)
- (L, P) -> (11, 15)
Step 3: Encryption
Encrypt each pair using matrix multiplication and take modulo 26.
For (H, E):
[3325][74]=[3⋅7+3⋅42⋅7+5⋅4]=[21+1214+20]=[3334]
Take modulo 26:
[3334]≡[78](mod26)
Convert back to letters: (7, 8) -> HI
For (L, P):
[3325][1115]=[3⋅11+3⋅152⋅11+5⋅15]=[33+4522+75]=[7897]
Take modulo 26:
[7897]≡[019](mod26)
Convert back to letters: (0, 19) -> AT
So, the ciphertext for "HELP" is "HIAT"
Step 4: Decryption
To decrypt, we need the inverse of the key matrix modulo 26.
Find the determinant of K:
det(K)=3⋅5−3⋅2=15−6=9
Find the modular inverse of the determinant modulo 26, which is 3 (since 9×3≡1(mod26)
Compute the inverse matrix:
K−1=19[5−3−23]≡3[5−3−23]≡[15−9−69]≡[1517209](mod26)
Decrypt the ciphertext "HIAT" using K−1
- Convert "HIAT" to numbers: H=7, I=8, A=0, T=19
For (H, I): [1517209][78]=[15⋅7+17⋅820⋅7+9⋅8]=[105+136140+72]=[241212]
Take modulo 26: [241212]≡[74](mod26)
Convert back to letters: (7, 4) -> HE
For (A, T):
[1517209][019]=[15⋅0+17⋅1920⋅0+9⋅19]=[0+3230+171]=[323171]
Take modulo 26: [323171]≡[1115](mod26)
Convert back to letters: (11, 15) -> LP
The decrypted plaintext is "HELP".
Python Code Hill Cipher
Comments
Post a Comment