Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Вариант 9
- * Напишите программу, позволяющую зашифровать и расшифровать сообщения с использованием одноразового блокнота.
- * Входные и выходные данные запишите в файл типа .txt.
- */
- #include <iostream>
- #include <fstream>
- #include <windows.h>
- using namespace std;
- // Генерация ключа
- string generateKey(int length)
- {
- string key;
- for (int i = 0; i < length; i++)
- {
- char randomChar = 'A' + (rand() % 26); // 'A' - чтобы были заглавные буквы ('a' - строчные)
- // 26 - столько букв в английском алфавите (если значение больше, то в ключе будут присутствовать служебные символы)
- key += randomChar;
- }
- return key;
- }
- // Шифровка сообщения
- void encryptMessage(string message, string key, string& encryptedMessage)
- {
- for (int i = 0; i < message.length(); i++)
- encryptedMessage += message[i] ^ key[i];
- }
- // Расшифровка сообщения
- void decryptMessage(string encryptedMessage, string key, string& decryptedMessage)
- {
- for (int i = 0; i < encryptedMessage.length(); i++)
- decryptedMessage += encryptedMessage[i] ^ key[i];
- }
- int main()
- {
- SetConsoleOutputCP(CP_UTF8);
- srand(time(NULL));
- string message, encryptedMessage, decryptedMessage;
- ifstream FileIn("input.txt");
- if (FileIn.is_open())
- {
- getline(FileIn, message);
- FileIn.close();
- }
- else
- {
- cerr << "Невозможно открыть input.txt" << endl;
- return 1;
- }
- cout << "Исходное сообщение (файл input.txt): " << message << endl;
- string key = generateKey(message.length());
- cout << "Сгенерированный ключ (файл key.txt): " << key << endl;
- encryptMessage(message, key, encryptedMessage);
- cout << "Зашифрованное сообщение (файл encrypted.txt): " << encryptedMessage << endl;
- decryptMessage(encryptedMessage, key, decryptedMessage);
- cout << "Расшифрованное сообщение (файл output.txt): " << decryptedMessage << endl;
- ofstream FileKey("key.txt");
- if (FileKey.is_open())
- {
- FileKey << key;
- FileKey.close();
- }
- else
- {
- cerr << "Невозможно открыть key.txt" << endl;
- return 1;
- }
- ofstream FileEn("encrypted.txt");
- if (FileEn.is_open())
- {
- FileEn << encryptedMessage;
- FileEn.close();
- }
- else
- {
- cerr << "Невозможно открыть encrypted.txt" << endl;
- return 1;
- }
- ofstream FileOut("output.txt");
- if (FileOut.is_open())
- {
- FileOut << decryptedMessage;
- FileOut.close();
- }
- else
- {
- cerr << "Невозможно открыть output.txt" << endl;
- return 1;
- }
- system("PAUSE");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment