-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathColumnarTranspositionCipher.cpp
123 lines (112 loc) · 2.68 KB
/
ColumnarTranspositionCipher.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
#include <iostream>
#include <map>
#include <string>
using namespace std;
string key = "HACK";
map<int, int> keyMap;
void setPermutationOrder()
{
int n = key.length();
for (int i = 0; i < n; i++)
{
keyMap[key[i]] = i;
}
}
// Encryption
string encrypt(string plainText)
{
int row, column, j;
string cipherText = "";
column = key.length();
row = plainText.length() / column;
if (plainText.length() % column)
{
row += 1;
}
char matrix[row][column];
for (int i = 0, k = 0; i < row; i++)
{
for (int j = 0; j < column;)
{
if (plainText[k] == '\0')
{
matrix[i][j] = '_';
j++;
}
if (isalpha(plainText[k]) || plainText[k] == ' ')
{
matrix[i][j] = plainText[k];
j++;
}
k++;
}
}
for (map<int, int>::iterator ii = keyMap.begin(); ii != keyMap.end(); ++ii)
{
j = ii->second;
for (int i = 0; i < row; i++)
{
// isalpha function checks if the passed character is an alphabet or not
if (isalpha(matrix[i][j]) || matrix[i][j] == ' ' || matrix[i][j] == '_')
{
cipherText += matrix[i][j];
}
}
}
return cipherText;
}
// Decryption
string decrypt(string cipherText)
{
int col = key.length();
int row = cipherText.length() / col;
char cipherMatrix[row][col];
for (int j = 0, k = 0; j < col; j++)
{
for (int i = 0; i < row; i++)
{
cipherMatrix[i][j] = cipherText[k++];
}
}
int index = 0;
for (map<int, int>::iterator ii = keyMap.begin(); ii != keyMap.end(); ++ii)
{
ii->second = index++;
}
char decCipher[row][col];
map<int, int>::iterator ii = keyMap.begin();
int k = 0;
for (int l = 0, j; key[l] != '\0'; k++)
{
j = keyMap[key[l++]];
for (int i = 0; i < row; i++)
{
decCipher[i][k] = cipherMatrix[i][j];
}
}
// Getting message using matrix
string message = "";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (decCipher[i][j] != '_')
{
message += decCipher[i][j];
}
}
}
return message;
}
int main()
{
string message;
fflush(stdin);
printf("Enter the Plain Text: ");
getline(cin, message);
setPermutationOrder();
string cipher = encrypt(message);
cout << "Cipher (Encrypted) Text: " << cipher << endl;
string plainText = decrypt(cipher);
cout << "Decrypted Text: " << plainText << endl;
}