-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
101 lines (84 loc) · 2.19 KB
/
main.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
#include <iostream>
#include <string>
#include <vector>
#include <bitset>
#include <random>
#include <sstream>
std::string input = "";
std::string msg = "";
std::string key = "";
char Xor(char x, char y){
if (x == y) {
return '0';
}
return '1';
}
std::string RetBitset(std::string str) {
std::string Bitset;
for (size_t i = 0; i < str.size(); i++) {
Bitset += std::bitset<8>(str.c_str()[i]).to_string();
}
return Bitset;
}
std::string RandomString(size_t length) {
auto randchar = []() -> char {
const char charset[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
const size_t max_index = (sizeof(charset) - 1);
return charset[rand() % max_index];
};
std::string str(length, 0);
std::generate_n(str.begin(), length, randchar);
return str;
}
std::string EncStr(std::string msg) {
std::string key = RandomString(msg.length());
std::cout << "Decryption key: " + key << std::endl;
std::string keyBitset = RetBitset(key);
std::string msgBitset = RetBitset(msg);
for (size_t i = 0; i < msgBitset.length(); i++)
{
msgBitset[i] = Xor(msgBitset[i], keyBitset[i]);
}
return msgBitset;
}
std::string DecStr(std::string msg, std::string key) {
std::string keyBitset = RetBitset(key);
for (size_t i = 0; i < msg.length(); i++)
{
msg[i] = Xor(msg[i], keyBitset[i]);
}
std::stringstream sstream(msg);
std::string output;
while (sstream.good())
{
std::bitset<8> bits;
sstream >> bits;
char c = char(bits.to_ulong());
output += c;
}
return output;
}
int main()
{
srand(time(0));
std::cout << "[1] Encrypt\n";
std::cout << "[2] Decrypt\n";
std::cin >> input;
if (input == "1") {
system("cls");
std::cout << "Message: ";
std::cin >> msg;
std::cout << "Encrypted: " + EncStr(msg) << std::endl;
}
else {
system("cls");
std::cout << "Message: ";
std::cin >> msg;
std::cout << "Key: ";
std::cin >> key;
std::cout << "Decrypted: " + DecStr(msg, key) << std::endl;
}
}