Hill cipher with key of length n^2
1. convert a message to a sequence of numbers modulo some modulus M. For example, take M = 26 and assign A = 0, B = 1, ..., Z = 25. Or M = 256 and use UTF-8 encoding or U.S. ASCII encoding.
2. Take the sequence of numbers from part (1), take them n at a time and encrypt them with the encryption key, which will be an n-by-n matrix of numbers modulo M. So for example if n = 3, then plaintext message p1 p2 p3 ... get transformed as
A p = c
where A is the n-by-n encryption matrix with its n^2 entries modulo M (this is the encryption key), p is an n-by-1 column vector of a block of n plaintext numbers, and c is an n-by-1 column vector of the corresponding ciphertext numbers.
3. Perform the reverse process of step 1, i.e., convert the sequence of ciphertext numbers back to the alphabet of the original message, for example, if M = 26 then 0 => A, 1 => B, ..., 25 => Z.
Deciphering works the same way, except you use a matrix B which is the inverse modulo M of the encryption matrix A.
The inverse of matrix:
a b
c d
is
d/D -b/D
-c/D a/D
where D = ad - bc must of course be nonzero.
Here it looks like you may be using modulo 26. If
2 7
3 1
is the decryption key, then follow steps 1 - 3 above to recover the plaintext. If instead that was the encryption key, then you must first find its inverse modulo 26:
The inverse of
2 7
3 1
is
1/D -7/D
-3/D 2/D
where D = 2*1 - 3*7 = 2 - 21 = -19 = 7 modulo 26. Since 7 * 15 = 105 = 4*26 + 1, we have 1/D = 1/7 = 15 modulo 26. So the key to decipher is
15 -105
-45 30
or
15 25
7 4
modulo 26.
Example:
message = NO
A => 0, B => 1, C => 2, ..., Z => 25
So NO corresponds to 13 14
Encrypt:
[ 2, 7 ] [ 13 ] = [ 20 ]
[ 3, 1 ] [ 14 ] = [ 1 ]
modulo 26. So "NO" encrypts to "UB"
Then "UB" decrypts to
[ 15, 25 ] [ 20 ] = [ 13 ]
[ 7, 4 ] [ 1 ] = [ 14 ]
modulo 26, so "UB" correctly decrypts back to "NO".
Dan