hill cipher encryption in c

Solutions on MaxInterview for hill cipher encryption in c by the best coders in the world

showing results for - "hill cipher encryption in c"
Marcus
26 Jan 2021
1#include<stdio.h>
2#include<math.h>
3 
4float encrypt[3][1], decrypt[3][1], a[3][3], b[3][3], mes[3][1], c[3][3];
5 
6void encryption();	//encrypts the message
7void decryption();	//decrypts the message
8void getKeyMessage();	//gets key and message from user
9void inverse();		//finds inverse of key matrix
10 
11void main() {
12	getKeyMessage();
13	encryption();
14	decryption();
15}
16 
17void encryption() {
18	int i, j, k;
19	
20	for(i = 0; i < 3; i++)
21		for(j = 0; j < 1; j++)
22			for(k = 0; k < 3; k++)
23				encrypt[i][j] = encrypt[i][j] + a[i][k] * mes[k][j];
24	
25	printf("\nEncrypted string is: ");
26	for(i = 0; i < 3; i++)
27		printf("%c", (char)(fmod(encrypt[i][0], 26) + 97));
28 
29}
30 
31void decryption() {
32	int i, j, k;
33	
34	inverse();
35	
36	for(i = 0; i < 3; i++)
37		for(j = 0; j < 1; j++)
38			for(k = 0; k < 3; k++)
39				decrypt[i][j] = decrypt[i][j] + b[i][k] * encrypt[k][j];
40	
41	printf("\nDecrypted string is: ");
42	for(i = 0; i < 3; i++)
43		printf("%c", (char)(fmod(decrypt[i][0], 26) + 97));
44	
45	printf("\n");
46}
47 
48void getKeyMessage() {
49	int i, j;
50	char msg[3];
51 
52	printf("Enter 3x3 matrix for key (It should be inversible):\n");
53	
54	for(i = 0; i < 3; i++)
55		for(j = 0; j < 3; j++) {
56			scanf("%f", &a[i][j]);
57			c[i][j] = a[i][j];
58		}
59	
60	printf("\nEnter a 3 letter string: ");
61	scanf("%s", msg);
62	
63	for(i = 0; i < 3; i++)
64		mes[i][0] = msg[i] - 97;
65}
66 
67void inverse() {
68	int i, j, k;
69	float p, q;
70	
71	for(i = 0; i < 3; i++)
72		for(j = 0; j < 3; j++) {
73			if(i == j)
74				b[i][j]=1;
75			else
76				b[i][j]=0;
77		}
78		
79	for(k = 0; k < 3; k++) {
80		for(i = 0; i < 3; i++) {
81			p = c[i][k];
82			q = c[k][k];
83				
84			for(j = 0; j < 3; j++) {
85				if(i != k) {
86					c[i][j] = c[i][j]*q - p*c[k][j];
87					b[i][j] = b[i][j]*q - p*b[k][j];
88				}
89			}
90		}
91	}
92	
93	for(i = 0; i < 3; i++)
94		for(j = 0; j < 3; j++)
95			b[i][j] = b[i][j] / c[i][i];
96	
97	printf("\n\nInverse Matrix is:\n");
98	for(i = 0; i < 3; i++) {
99		for(j = 0; j < 3; j++)
100			printf("%d ", b[i][j]);
101		
102		printf("\n");
103	}
104}
105
Kurtis
17 Nov 2018
1hill cipher encryption and decryption