1 #include <stdio.
h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #define SIZE 30
6
7 void toLowerCase(char plain[], int ps)
8 {
9 int i;
10 for (i = 0; i < ps; i++) {
11 if (plain[i] > 64 && plain[i] < 91)
12 plain[i] += 32;
13 }
14 }
15
16 int removeSpaces(char* plain, int ps)
17 {
18 int i, count = 0;
19 for (i = 0; i < ps; i++)
20 if (plain[i] != ' ')
21 plain[count++] = plain[i];
22 plain[count] = '\0';
23 return count;
24 }
25
26 void generateKeyTable(char key[], int ks, char keyT[5][5])
27 {
28 int i, j, k, flag = 0, *dicty;
29
30 dicty = (int*)calloc(26, sizeof(int));
31 for (i = 0; i < ks; i++) {
32 if (key[i] != 'j')
33 dicty[key[i] - 97] = 2;
34 }
35
36 dicty['j' - 97] = 1;
37
38 i = 0;
39 j = 0;
40
41 for (k = 0; k < ks; k++) {
42 if (dicty[key[k] - 97] == 2) {
43 dicty[key[k] - 97] -= 1;
44 keyT[i][j] = key[k];
45 j++;
46 if (j == 5) {
47 i++;
48 j = 0;
49 }
50 }
51 }
52
53 for (k = 0; k < 26; k++) {
54 if (dicty[k] == 0) {
55 keyT[i][j] = (char)(k + 97);
56 j++;
57 if (j == 5) {
58 i++;
59 j = 0;
60 }
61 }
62 }
63 }
64
65 void search(char keyT[5][5], char a, char b, int arr[])
66 {
67 int i, j;
68
69 if (a == 'j')
70 a = 'i';
71 else if (b == 'j')
72 b = 'i';
73
74 for (i = 0; i < 5; i++) {
75
76 for (j = 0; j < 5; j++) {
77
78 if (keyT[i][j] == a) {
79 arr[0] = i;
80 arr[1] = j;
81 }
82 else if (keyT[i][j] == b) {
83 arr[2] = i;
84 arr[3] = j;
85 }
86 }
87 }
88 }
89
90 int mod5(int a) { return (a % 5); }
91
92 int prepare(char str[], int ptrs)
93 {
94 if (ptrs % 2 != 0) {
95 str[ptrs++] = 'z';
96 str[ptrs] = '\0';
97 }
98 return ptrs;
99 }
100
101 void encrypt(char str[], char keyT[5][5], int ps)
102 {
103 int i, a[4];
104
105 for (i = 0; i < ps; i += 2) {
106
107 search(keyT, str[i], str[i + 1], a);
108
109 if (a[0] == a[2]) {
110 str[i] = keyT[a[0]][mod5(a[1] + 1)];
111 str[i + 1] = keyT[a[0]][mod5(a[3] + 1)];
112 }
113 else if (a[1] == a[3]) {
114 str[i] = keyT[mod5(a[0] + 1)][a[1]];
115 str[i + 1] = keyT[mod5(a[2] + 1)][a[1]];
116 }
117 else {
118 str[i] = keyT[a[0]][a[3]];
119 str[i + 1] = keyT[a[2]][a[1]];
120 }
121 }
122 }
123
124 void encryptByPlayfairCipher(char str[], char key[])
125 {
126 char ps, ks, keyT[5][5];
127
128 ks = strlen(key);
129 ks = removeSpaces(key, ks);
130 toLowerCase(key, ks);
131
132 ps = strlen(str);
133 toLowerCase(str, ps);
134 ps = removeSpaces(str, ps);
135
136 ps = prepare(str, ps);
137
138 generateKeyTable(key, ks, keyT);
139
140 encrypt(str, keyT, ps);
141 }
142
143 int main()
144 {
145 char str[SIZE], key[SIZE];
146
147 strcpy(key, "Monarchy");
148 printf("Key text: %s\n", key);
149
150 strcpy(str, "instruments");
151 printf("Plain text: %s\n", str);
152
153 encryptByPlayfairCipher(str, key);
154
155 printf("Cipher text: %s\n", str);
156
157 return 0;
158 }
159