-
Notifications
You must be signed in to change notification settings - Fork 0
/
ColumnarTransposition.cpp
108 lines (75 loc) · 1.98 KB
/
ColumnarTransposition.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
#include <bits/stdc++.h>
using namespace std;
string encrypt(string text, string key)
{
string result;
char matrix[100][100] = {0};
int line = ceil(1.0 * text.size() / key.size());
for(int i = 0; i < line; ++i) {
for(int j = 0; j< key.size() ; ++j) {
if (i * key.size() + j <= text.size() - 1)
{
matrix[i][j] = text[i*key.size() + j];
}
}
}
for (int j = 0; j < key.size(); ++j) {
if (matrix[line-1][j] == 0) {
matrix[line-1][j] = 'X';
}
}
vector<pair<int, int>> values;
for (int i = 0; i < key.size(); ++i) {
values.push_back({key[i],i});
}
sort(values.begin(), values.end());
for (auto it : values) {
for (int i = 0; i < line; ++i) {
if(matrix[i][it.second] != 0) {
result += matrix[i][it.second];
}
}
}
return result;
}
string decrypt(string text, string key)
{
string result;
char matrix[100][100] = {0};
int line = ceil(1.0 * text.size() / key.size());
vector<pair<int, int>> values;
for (int i = 0; i < key.size(); ++i) {
values.push_back({key[i],i});
}
sort(values.begin(),values.end());
int k = 0;
for (auto it : values) {
for (int i = 0; i < line; ++i)
matrix[i][it.second] = text[k++];
}
for (int i = 0; i < line; ++i) {
for (int j = 0; j < key.size(); ++j) {
if (matrix[i][j] != 'X') {
result += matrix[i][j];
}
}
}
return result;
}
int main()
{
string text;
cout<<"Plainext: ";
getline(cin, text);
transform(text.begin(), text.end(), text.begin(), ::toupper);
text.erase(remove_if(text.begin(), text.end(), ::isspace), text.end());
string key;
cout<<"Key: ";
getline(cin, key);
transform(key.begin(), key.end(), key.begin(), ::toupper);
key.erase(remove_if(key.begin(), key.end(), ::isspace), key.end());
string cipher = encrypt(text, key);
cout<<"Ciphertext: "<<cipher<<endl;
cout<<"Result: "<<decrypt(cipher, key);
return 0;
}