By Sri Sakthi M
Implementation of Encryption and Decryption using Hill Cipher in C++. Hill cipher is a polygraphic substitution cipher.
Hill Cipher encrypts a group of letters called a polygraph.
This method makes use of matrices from mathematics.
Encryption: The key and plaintext are converted into matrix format according to the positions like a=0 to z=25. The matrices are multiplied against modulo 26. The key matrix should have an inverse to decrypt the message.
C = KP mod 26
where K is the Key and P is the plain text.
Decryption: The encrypted message is multiplied by the inverse of the key matrix used for encryption against modulo 26 to get the decrypted message.
P = K-1C mod 26
where K is the Key and C is the ciphertext.
2 3
3 6
Message string ‘ATTACK’ in matrix form −
0 19 2
19 0 10
After multiplying the above two matrices we get,
5 12 8
10 5 14
Which will be the encrypted message ‘FKMFIO’
The inverse of the key matrix is
2 25
25 18
Now after multiplying the inverse matrix of the key matrix with the encrypted message matrix is
0 19 2
19 0 10
Which is the original message string is ‘ATTACK’.
Considering if the key matrix is 3*3.
#include
#include
using namespace std;
float e[3][1], d[3][1], a[3][3], b[3][3], ms[3][1], m[3][3];
void getKey() {
int i, j;
char me[3];
cout<<"Enter 3x3 matrix for key (should have inverse):\n";
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
cin>>a[i][j];
m[i][j] = a[i][j];
}
cout<<"\nEnter a string of 3 letter(use A through Z): ";
cin>>me;
for(i = 0; i < 3; i++)
ms[i][0] = me[i] - 65;
}
void encryption() {
int i, j, k;
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
e[i][j] = e[i][j] + a[i][k] * ms[k][j];
cout<<"\nEncrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(e[i][0], 26) + 65);
}
void inverse() {
int i, j, k;
float p, q;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
if(i == j)
b[i][j]=1;
else
b[i][j]=0;
}
for(k = 0; k < 3; k++) {
for(i = 0; i < 3; i++) {
p = m[i][k];
q = m[k][k];
for(j = 0; j < 3; j++) {
if(i != k) {
m[i][j] = m[i][j]*q - p*m[k][j];
b[i][j] = b[i][j]*q - p*b[k][j];
}
}
}
}
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
b[i][j] = b[i][j] / m[i][i];
cout<<"\n\nInverse Matrix is:\n";
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++)
cout<<b[i][j]<<" ";
cout<<"\n";
}
}
void decryption() {
int i, j, k;
inverse();
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
d[i][j] = d[i][j] + b[i][k] * e[k][j];
cout<<"\nDecrypted string is: ";
for(i = 0; i < 3; i++)
cout<<(char)(fmod(d[i][0], 26) + 65);
cout<<"\n";
}
int main() {
getKey();
encryption();
decryption();
}
Enter 3x3 matrix for key (should have inverse): 1 0 1 2 4 0 3 5 6 Enter a string of 3 letter(use A through Z): ACT Encrypted string is: TIU Inverse Matrix is: 1.09091 0.227273 -0.181818 -0.545455 0.136364 0.0909091 -0.0909091 -0.227273 0.181818 Decrypted string is: ACT
Submitted by Sri Sakthi M (Sakthi)
Download packets of source code on Coders Packet
Comments