-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3_4-6_substitution_cipher_text.cpp
98 lines (76 loc) · 2.24 KB
/
3_4-6_substitution_cipher_text.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
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define D_NUM_CIPHER_CHARS 26
using namespace std;
/*
Substitution cipher, generating random cipher array, ciphering a text and converting it back, all letter UPPER-CASE.
Ciphering letters only, not punctuations. Using only arrays.
*/
int main()
{
char plainText[] = "THIS IS AN EXAMPLE PLAIN TEXT. THE TEXT IS CIPHERED \n"
"USING CHAR ARRAY WHICH IS GENERATED RANDOMLY IN CODE.";
int textSize = sizeof(plainText);
char cipherText[textSize];
// Generate cipherChars randomly (exercise 3.6)
char tempAlphabet[D_NUM_CIPHER_CHARS] = {
'A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V',
'W','X','Y','Z'
};
char cipherChars[D_NUM_CIPHER_CHARS];
srand(time(NULL));
int chIdx = 0;
int randNum = 0;
for (int i = 0; i < D_NUM_CIPHER_CHARS; i++)
{
chIdx = i;
while (chIdx == i || tempAlphabet[chIdx] == -1)
{
chIdx = rand() % D_NUM_CIPHER_CHARS;
}
cipherChars[i] = tempAlphabet[chIdx];
tempAlphabet[chIdx] = -1;
}
char ch = 0;
// Producing cipher text (exercise 3.4)
for (int i = 0; i < textSize; i++)
{
if (plainText[i] < 'A' || plainText[i] > 'Z')
{
cipherText[i] = plainText[i];
}
else
{
cipherText[i] = cipherChars[plainText[i] - 'A'];
}
}
cout << cipherText << endl;
// Converting back to plain text (exercise 4.5)
cout << "Converting to plain text:" << endl;
// Array generated to find corresponding character in alphabet faster
char cipherCharsIdxMap[D_NUM_CIPHER_CHARS];
for (int i = 0; i < D_NUM_CIPHER_CHARS; i++)
{
cipherCharsIdxMap[cipherChars[i] - 'A'] = i + 'A';
}
char plainText2[textSize];
plainText2[0] = 0;
for (int i = 0; i < textSize; i++)
{
if (cipherText[i] < 'A' || cipherText[i] > 'Z')
{
plainText2[i] = cipherText[i];
}
else
{
plainText2[i] = cipherCharsIdxMap[cipherText[i]-'A'];
chIdx = 0;
}
}
cout << plainText2 << endl;
cin.get();
return 0;
}