-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRailFence Cipher.cpp
More file actions
111 lines (93 loc) · 2.54 KB
/
RailFence Cipher.cpp
File metadata and controls
111 lines (93 loc) · 2.54 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
104
105
106
107
108
109
110
111
/*
* RailFence Cipher
*
* author: dipta
* created: 05-Oct-2018 01:07:20
*
*/
#include<bits/stdc++.h>
using namespace std;
char cptext[1000];
char railMatrix[100][1000];
int Input(char [], int );
void encrypt(char [], int );
void decrypt(char [], int );
void prePosses (char [], int );
void railFenceCipher (char [], int );
int main ()
{
char str[1000];
int key;
printf("\tRail Fence Cipher Algorithm\n");
printf("\t---------------------------\n");
railFenceCipher(str, key); /* algorithm */
return 0;
}
void railFenceCipher (char str[], int key) {
int choice;
while(1) {
printf("\n\t\t(1) Encrypt");
printf("\n\t\t(2) Decrypt");
printf("\n\t\t(3) Exit");
printf("\n\t\tEnter your choice: "); scanf("%d", &choice);
getchar();
switch(choice) {
case 1:
key = Input(str, key);
prePosses(str, key);
encrypt(str, key); printf("\n\t\tEncrypt text: %s\n", cptext);
break;
case 2:
key = Input(str, key);
prePosses(str, key);
decrypt(str, key); printf("\n\t\tDecrypt text: %s\n", cptext);
break;
default:
exit(0);
break;
}
}
}
int Input(char str[], int key) {
printf("\n\t\tEnter plain text: "); gets(str);
printf("\t\tEnter key: "); scanf("%d", &key);
return key;
}
void encrypt(char str[], int key) {
int msgLen = strlen(str);
int in = 0;
for(int i = 0; i < key; ++i)
for(int j = 0; j < msgLen; ++j)
if(railMatrix[i][j] != '\n')
cptext[in++] = railMatrix[i][j];
cptext[in] = '\0';
}
void decrypt(char str[], int key) {
int msgLen = strlen(str);
int in = 0;
for(int i = 0; i < key; ++i)
for(int j = 0; j < msgLen; ++j)
if(railMatrix[i][j] != '\n')
railMatrix[i][j] = str[in++];
int row=0, col=0, k=-1;
for(int i=0, in=0; i < msgLen; ++i){
cptext[in++] = railMatrix[row][col++];
if(row == 0 || row == key-1)
k= k * (-1);
row = row + k;
}
cptext[in] = '\0';
}
void prePosses (char str[], int key) {
int msgLen = strlen(str);
int k = -1, row = 0, col = 0;
for(int i = 0; i < key; ++i)
for(int j = 0; j < msgLen; ++j)
railMatrix[i][j] = '\n';
for(int i = 0; i < msgLen; ++i){
railMatrix[row][col++] = str[i];
if(row == 0 || row == key-1)
k= k * (-1);
row = row + k;
}
}