-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrail-fence.cpp
91 lines (87 loc) · 2.28 KB
/
rail-fence.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
#include <iostream>
#include <string>
using namespace std;
string encryptRailFence(string plaintext, int key) {
string ciphertext;
int len = plaintext.length();
char rail[key][len];
for (int i = 0; i < key; i++) {
for (int j = 0; j < len; j++) {
rail[i][j] = '\n';
}
}
bool dir_down = false;
int row = 0, col = 0;
for (int i = 0; i < len; i++) {
if (row == 0 || row == key-1) {
dir_down = !dir_down;
}
rail[row][col++] = plaintext[i];
dir_down ? row++ : row--;
}
for (int i = 0; i < key; i++) {
for (int j = 0; j < len; j++) {
if (rail[i][j] != '\n') {
ciphertext.push_back(rail[i][j]);
}
}
}
return ciphertext;
}
string decryptRailFence(string ciphertext, int key) {
string plaintext;
int len = ciphertext.length();
char rail[key][len];
for (int i = 0; i < key; i++) {
for (int j = 0; j < len; j++) {
rail[i][j] = '\n';
}
}
bool dir_down;
int row = 0, col = 0;
for (int i = 0; i < len; i++) {
if (row == 0) {
dir_down = true;
}
if (row == key-1) {
dir_down = false;
}
rail[row][col++] = '*';
dir_down ? row++ : row--;
}
int index = 0;
for (int i = 0; i < key; i++) {
for (int j = 0; j < len; j++) {
if (rail[i][j] == '*' && index < len) {
rail[i][j] = ciphertext[index++];
}
}
}
row = 0, col = 0;
for (int i = 0; i < len; i++) {
if (row == 0) {
dir_down = true;
}
if (row == key-1) {
dir_down = false;
}
if (rail[row][col] != '\n') {
plaintext.push_back(rail[row][col++]);
}
dir_down ? row++ : row--;
}
return plaintext;
}
int main() {
string plaintext, ciphertext, decryptedtext;
int key;
cout << "Enter the plaintext: ";
getline(cin, plaintext);
cout << "Enter the key: ";
cin >> key;
ciphertext = encryptRailFence(plaintext, key);
cout << "Encrypted text: " << ciphertext << endl;
decryptedtext = decryptRailFence(ciphertext, key);
cout << "Decrypted text: " << decryptedtext << endl;
return 0;
}