-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathColumnarTransposition.cpp
More file actions
103 lines (78 loc) · 2.15 KB
/
ColumnarTransposition.cpp
File metadata and controls
103 lines (78 loc) · 2.15 KB
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
#ifndef COLUMNARTRANSPOSITION_C
#define COLUMNARTRANSPOSITION_C
#include "StreamCipher.cpp"
#include <algorithm>
class ColumnarTransposition : public StreamCipher {
private:
std::string key;
public:
ColumnarTransposition(std::string key) {
this->key = toLowerCase(key);
}
std::string encrypt(std::string plain) override {
plain = toLowerCase(plain);
std::vector<int> spaces = removeSpaces(plain);
int rows = (int)(plain.size() / key.size());
if (plain.size() % key.size() != 0) {
rows++;
}
std::vector<std::vector<char>> matrix(rows, std::vector<char>(key.size(), ' '));
// In by rows
int k = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < key.size(); j++) {
if (k < plain.size()) {
matrix[i][j] = plain[k++];
}
}
}
std::vector<std::pair<char, int>> keyIndex;
for (int i = 0; i < key.size(); i++) {
keyIndex.push_back(std::make_pair(key[i], i));
}
std::sort(keyIndex.begin(), keyIndex.end());
// out by columns
std::string cipher;
for (int i = 0; i < key.size(); i++) {
int index = keyIndex[i].second;
for (int j = 0; j < rows; j++) {
if (matrix[j][index] != ' ')
cipher.push_back(matrix[j][index]);
}
}
int i = (int)key.size();
while (i < cipher.size()) {
cipher.insert(i, " ");
i += (int)key.size() + 1;
}
return cipher;
}
std::string decrypt(std::string cipher) override {
std::vector<int> spaces = removeSpaces(cipher);
int rows = (int)(cipher.size() / key.size());
if (cipher.size() % key.size() != 0) {
rows++;
}
std::vector<std::vector<char>> matrix(rows, std::vector<char>(key.size(), ' '));
int k = 0;
for (int i = 0; i < key.size(); i++) {
for (int j = 0; j < rows; j++) {
matrix[j][i] = cipher[k++];
}
}
std::vector<std::pair<char, int>> keyIndex;
for (int i = 0; i < key.size(); i++) {
keyIndex.push_back(std::make_pair(key[i], i));
}
std::sort(keyIndex.begin(), keyIndex.end());
std::string plain;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < key.size(); j++) {
int index = keyIndex[j].second;
plain.push_back(matrix[i][index]);
}
}
return plain;
}
};
#endif // !COLUMNARTRANSPOSITION_C