forked from Adi8080/Hactoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHill Cipher.cpp
129 lines (101 loc) · 2.76 KB
/
Hill Cipher.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// C++ code to implement Hill Cipher
#include <bits/stdc++.h>
using namespace std;
string input;
void init_code()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE
}
void Key(string letterkey, int Keymatrix[][3])
{
int k = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Keymatrix[i][j] = (letterkey[k]) % 65;
k++;
}
}
}
void encryption(int cipherMatrix[][1],
int Keymatrix[][3],
int inputVector[][1])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 1; j++)
{
cipherMatrix[i][j] = 0;
for (int x = 0; x < 3; x++)
{
cipherMatrix[i][j] +=
Keymatrix[i][x] * inputVector[x][j];
}
cipherMatrix[i][j] = cipherMatrix[i][j] % 26;
}
}
}
void decryption(int outputMatrix[][1],
int inverseKeymatrix[][3],
int cipherMatrix[][1])
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 1; j++)
{
outputMatrix[i][j] = 0;
for (int x = 0; x < 3; x++)
{
outputMatrix[i][j] +=
inverseKeymatrix[i][x] * cipherMatrix[x][j];
}
outputMatrix[i][j] = outputMatrix[i][j] % 26;
}
}
}
void HillCipher(string message, string letterkey)
{
int Keymatrix[3][3];
Key(letterkey, Keymatrix);
int inputVector[3][1];
for (int i = 0; i < 3; i++)
inputVector[i][0] = (message[i]) % 65;
int cipherMatrix[3][1];
int outputMatrix[3][1];
encryption(cipherMatrix, Keymatrix, inputVector);
string CipherText;
for (int i = 0; i < 3; i++)
CipherText += cipherMatrix[i][0] + 65;
cout << "Ciphertext:" << CipherText;
int inverseKeymatrix[3][3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
cin >> inverseKeymatrix[i][j];
}
string outputText = "";
decryption(outputMatrix,
inverseKeymatrix,
cipherMatrix);
for (int i = 0; i < 3; i++)
outputText += outputMatrix[i][0] + 65;
if (outputText == input)
{
cout << "\n" << "-----KEY MATCHED!-----" << "\n";
cout << "Output:" << outputText;
}
else
cout << "\n" << "SORRY! WRONG KEY";
}
int main()
{
init_code();
cin >> input;
string letterkey = "GYBNQKURP";
HillCipher(input, letterkey);
return 0;
}