-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXOR_cipher.cpp
More file actions
46 lines (38 loc) · 1.64 KB
/
XOR_cipher.cpp
File metadata and controls
46 lines (38 loc) · 1.64 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
#include <iostream>
#include <string>
// Функция для шифрования/дешифрования с помощью XOR-ключа
std::string xor_cipher(const std::string &input, const std::string &key) {
std::string output;
output.reserve(input.size());
for (size_t i = 0; i < input.size(); ++i) {
// Применяем XOR между байтом и соответствующим байтом ключа (циклически)
char cipher_char = input[i] ^ key[i % key.size()];
output.push_back(cipher_char);
}
return output;
}
int main() {
std::string plaintext;
std::string key;
// Ввод исходного текста и ключа
std::cout << "Введите текст для шифрования: ";
std::getline(std::cin, plaintext);
std::cout << "Введите ключ (строка произвольной длины): ";
std::getline(std::cin, key);
if (key.empty()) {
std::cerr << "Ключ не может быть пустым!" << std::endl;
return 1;
}
// Шифрование
std::string ciphertext = xor_cipher(plaintext, key);
// Для удобства выводим в шестнадцатеричном виде
std::cout << "Зашифрованный текст (hex): ";
for (unsigned char c : ciphertext) {
printf("%02X", c);
}
std::cout << std::endl;
// Дешифрование (применяем ту же функцию)
std::string decrypted = xor_cipher(ciphertext, key);
std::cout << "Дешифрованный текст: " << decrypted << std::endl;
return 0;
}