Обьедини все эти коды и добавь выбор того, что необходимо… · The Chat Archive
Explore / Programming Обьедини все эти коды и добавь выбор того, что необходимо сделать, по типу:… Save Share Download ▾ ReportОбьедини все эти коды и добавь выбор того, что необходимо сделать, по типу: Расшифровать/ Зашифровать, Русский/Английский
Код 1:
#include
#include
#include
#include
#include
#include
#include
std::string vigenere_decrypt(const std::string& ciphertext, const std::string& key) {
std::string decrypted_text;
int key_length = key.length();
std::string upper_key = key;
std::transform(upper_key.begin(), upper_key.end(), upper_key.begin(), ::toupper);
for (size_t i = 0; i < ciphertext.length(); ++i) {
char char_upper = std::toupper(ciphertext[i]);
if (std::isalpha(char_upper)) {
char key_char = upper_key[i % key_length];
int key_shift = key_char - 'A';
char decrypted_char = ((char_upper - 'A' - key_shift + 26) % 26 + 'A';
decrypted_text.push_back(decrypted_char);
} else {
decrypted_text.push_back(ciphertext[i]);
}
}
return decrypted_text;
}
double calculate_index_of_coincidence(const std::string& text) {
std::map<char, int> frequencies;
for (char c : text) {
frequencies[c]++;
}
double n = text.length();
double ic = 0.0;
for (const auto& pair : frequencies) {
ic += pair.second * (pair.second - 1);
}
ic /= (n * (n - 1));
return ic;
}
std::map<int, double> find_key_length(const std::string& ciphertext, int max_key_length = 20) {
std::map<int, double> likely_key_lengths;
for (int key_len = 1; key_len <= max_key_length; ++key_len) {
double ic_sum = 0.0;
for (int i = 0; i < key_len; ++i) {
std::string subtext;
for (size_t j = i; j < ciphertext.length(); j += key_len) {
subtext.push_back(ciphertext[j]);
}
ic_sum += calculate_index_of_coincidence(subtext);
}
double average_ic = ic_sum / key_len;
likely_key_lengths[key_len] = average_ic;
}
return likely_key_lengths;
}
int find_shift(const std::string& subtext, const std::map<char, double>& frequencies) {
std::map<char, int> text_frequencies;
for (char c : subtext) {
text_frequencies[std::toupper(c)]++;
}
int total = 0;
for (const auto& pair : text_frequencies) {
if (frequencies.find(pair.first) != frequencies.end()) {
total += pair.second;
}
}
int min_diff = INT_MAX;
int best_shift = 0;
for (int shift = 0; shift < 26; ++shift) {
int diff = 0;
for (const auto& pair : frequencies) {
char shifted_char = ((pair.first - 'A' + shift) % 26 + 'A');
double expected_freq = pair.second * total;
double actual_freq = text_frequencies[shifted_char];
diff += std::abs(expected_freq - actual_freq);
}
if (diff < min_diff) {
min_diff = diff;
best_shift = shift;
}
}
return best_shift;
}
std::string find_key(const std::string& ciphertext, int key_length, const std::map<char, double>& frequencies) {
std::string key;
Assistant2025-03-13 07:09 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Mar 13, 2025
Added to archive Nov 16, 2026
ID 01m7h42j0r6828d4x9t8m7adkvSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 927194182fef967f6a4db21d72256a9a
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
for (int i = 0; i < key_length; ++i) {
std::string subtext;
for (size_t j = i; j < ciphertext.length(); j += key_length) {
subtext.push_back(ciphertext[j]);
}
int shift = find_shift(subtext, frequencies);
key.push_back(shift + 'A');
}
return key;
std::string read_file(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Ошибка: файл " << filename << " не может быть открыт.\n";
exit(1);
}
std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator());
file.close();
return content;
}
int main() {
std::string input_text = read_file(""C:\Users\user\documents\en_text_encrypted.txt");
std::transform(input_text.begin(), input_text.end(), input_text.begin(), ::toupper);
input_text.erase(std::remove_if(input_text.begin(), input_text.end(), [](char c) { return !std::isalpha(c); }), input_text.end());
std::cout << "Шифротекст:\n" << input_text << "\n";
auto possible_key_lengths = find_key_length(input_text);
double ideal_ic = 0.068;
std::vector<std::pair<int, double>> sorted_key_lengths(possible_key_lengths.begin(), possible_key_lengths.end());
std::sort(sorted_key_lengths.begin(), sorted_key_lengths.end(), [ideal_ic](const std::pair<int, double>& a, const std::pair<int, double>& b) {
return std::abs(a.second - ideal_ic) < std::abs(b.second - ideal_ic);
});
std::map<char, double> english_frequencies = {
{'A', 0.082}, {'B', 0.015}, {'C', 0.028}, {'D', 0.043}, {'E', 0.13}, {'F', 0.022},
{'G', 0.02}, {'H', 0.061}, {'I', 0.07}, {'J', 0.0015}, {'K', 0.0077}, {'L', 0.04},
{'M', 0.024}, {'N', 0.067}, {'O', 0.075}, {'P', 0.019}, {'Q', 0.00095}, {'R', 0.06},
{'S', 0.063}, {'T', 0.091}, {'U', 0.028}, {'V', 0.0098}, {'W', 0.024}, {'X', 0.0015},
{'Y', 0.02}, {'Z', 0.00074}
};
for (size_t i = 0; i < 8 && i < sorted_key_lengths.size(); ++i) {
int key_length = sorted_key_lengths[i].first;
std::string key = find_key(input_text, key_length, english_frequencies);
std::cout << "Длина ключа: " << key_length << "\n";
std::cout << "Найденный ключ: " << key << "\n";
std::string decrypted_text = vigenere_decrypt(input_text, key);
std::cout << "Расшифрованный текст:\n" << decrypted_text << "\n\n";
}
return 0;
Код 2:
#include
#include
#include
#include
#include
std::string vigenere_encrypt(const std::string& plain_text, const std::string& key) {
std::string encrypted_text;
int key_length = key.length();
std::string upper_key = key;
std::transform(upper_key.begin(), upper_key.end(), upper_key.begin(), ::toupper);
for (size_t i = 0; i < plain_text.length(); ++i) {
char c = plain_text[i];
if (std::isalpha(c)) {
char key_char = upper_key[i % key_length];
int shift = key_char - 'A';
if (std::islower(c)) {
encrypted_text.push_back(((c - 'a' + shift) % 26 + 'a'));
}
else {
encrypted_text.push_back(((c - 'A' + shift) % 26 + 'A'));
}
}
else {
encrypted_text.push_back(c);
}
}
return encrypted_text;
std::string clean_key(const std::string& key) {
std::string cleaned_key;
for (char c : key) {
if (std::isalpha(c)) {
cleaned_key.push_back(c);
}
}
return cleaned_key;
}
std::string read_file(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Ошибка: файл " << filename << " не может быть открыт.\n";
exit(1);
}
std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator());
file.close();
return content;
}
void write_file(const std::string& filename, const std::string& content) {
std::ofstream file(filename);
if (!file.is_open()) {
std::cerr << "Ошибка: файл " << filename << " не может быть открыт для записи.\n";
exit(1);
}
file << content;
file.close();
}
std::string prepare_text(const std::string& text) {
std::string prepared_text;
for (char c : text) {
if (std::isalpha(c)) {
prepared_text.push_back(std::toupper(c));
}
}
return prepared_text;
}
int main() {
std::string key = read_file("C:\Users\kiril\OneDrive\Рабочий стол\Мои\1\en\key.txt");
key = clean_key(key);
if (key.empty()) {
std::cerr << "Ошибка: ключ не может быть пустым после удаления лишних символов.\n";
return 1;
}
std::string input_text = read_file("C:\\Users\\kiril\\OneDrive\\Рабочий стол\\Мои\\1\\en\\en_text_input.txt");
std::string plain_text = prepare_text(input_text);
std::string encrypted_text = vigenere_encrypt(plain_text, key);
std::cout << "Ключ: " << key << "\n";
std::cout << "Зашифрованный текст: " << encrypted_text << "\n";
write_file("en_text_encrypted.txt", encrypted_text);
return 0;
Код 3:
#include
#include
#include
#include
#include
#include
#include
std::string vigenere_decrypt(const std::string& ciphertext, const std::string& key) {
std::string decrypted_text;
int key_length = key.length();
std::string upper_key = key;
std::transform(upper_key.begin(), upper_key.end(), upper_key.begin(), ::toupper);
for (size_t i = 0; i < ciphertext.length(); ++i) {
char char_upper = std::toupper(ciphertext[i]);
if ((char_upper >= 'A' && char_upper <= 'Z') || (char_upper >= 'А' && char_upper <= 'Я')) {
char key_char = upper_key[i % key_length];
int key_shift = (key_char >= 'А' && key_char <= 'Я') ? (key_char - 'А') : (key_char - 'A');
char decrypted_char = (char_upper - 'А' - key_shift + 32) % 32 + 'А';
decrypted_text.push_back(decrypted_char);
}
else {
decrypted_text.push_back(ciphertext[i]);
}
}
return decrypted_text;
double calculate_index_of_coincidence(const std::string& text) {
std::map<char, int> frequencies;
for (char c : text) {
frequencies[c]++;
}
double n = text.length();
double ic = 0.0;
for (const auto& pair : frequencies) {
ic += pair.second * (pair.second - 1);
}
ic /= (n * (n - 1));
return ic;
std::map<int, double> find_key_length(const std::string& ciphertext, int max_key_length = 30) {
std::map<int, double> likely_key_lengths;
for (int key_len = 1; key_len <= max_key_length; ++key_len) {
double ic_sum = 0.0;
for (int i = 0; i < key_len; ++i) {
std::string subtext;
for (size_t j = i; j < ciphertext.length(); j += key_len) {
subtext.push_back(ciphertext[j]);
}
ic_sum += calculate_index_of_coincidence(subtext);
}
double average_ic = ic_sum / key_len;
likely_key_lengths[key_len] = average_ic;
}
return likely_key_lengths;
int find_shift(const std::string& subtext, const std::map<char, double>& frequencies) {
std::map<char, int> text_frequencies;
for (char c : subtext) {
text_frequencies[std::toupper(c)]++;
}
int total = 0;
for (const auto& pair : text_frequencies) {
if (frequencies.find(pair.first) != frequencies.end()) {
total += pair.second;
}
}
int min_diff = INT_MAX;
int best_shift = 0;
for (int shift = 0; shift < 32; ++shift) {
int diff = 0;
for (const auto& pair : frequencies) {
char shifted_char = ((pair.first - 'А' + shift) % 32) + 'А';
double expected_freq = pair.second * total;
double actual_freq = text_frequencies[shifted_char];
diff += std::abs(expected_freq - actual_freq);
}
if (diff < min_diff) {
min_diff = diff;
best_shift = shift;
}
}
return best_shift;
std::string find_key(const std::string& ciphertext, int key_length, const std::map<char, double>& frequencies) {
std::string key;
for (int i = 0; i < key_length; ++i) {
std::string subtext;
for (size_t j = i; j < ciphertext.length(); j += key_length) {
subtext.push_back(ciphertext[j]);
}
int shift = find_shift(subtext, frequencies);
key.push_back(shift + 'А');
}
return key;
int main() {
std::ifstream file("C:\Users\user\documents\rus_text_encrypted.txt");
if (!file.is_open()) {
std::cerr << "Ошибка: файл не найден или не может быть открыт.\n";
return 1;
}
std::string input_text((std::istreambuf_iterator(file)), std::istreambuf_iterator());
file.close();
input_text.erase(std::remove_if(input_text.begin(), input_text.end(), [](char c) { return !std::isalpha(c); }), input_text.end());
std::transform(input_text.begin(), input_text.end(), input_text.begin(), ::toupper);
std::cout << "Шифротекст:\n" << input_text << "\n";
auto possible_key_lengths = find_key_length(input_text);
double ideal_ic = 0.068;
std::vector<std::pair<int, double>> sorted_key_lengths(possible_key_lengths.begin(), possible_key_lengths.end());
std::sort(sorted_key_lengths.begin(), sorted_key_lengths.end(), [ideal_ic](const std::pair<int, double>& a, const std::pair<int, double>& b) {
return std::abs(a.second - ideal_ic) < std::abs(b.second - ideal_ic);
});
std::map<char, double> russian_frequencies = {
{'А', 0.080}, {'Б', 0.015}, {'В', 0.045}, {'Г', 0.017}, {'Д', 0.030}, {'Е', 0.085}, {'Ж', 0.009},
{'З', 0.016}, {'И', 0.073}, {'Й', 0.010}, {'К', 0.035}, {'Л', 0.045}, {'М', 0.032}, {'Н', 0.067}, {'О', 0.109},
{'П', 0.028}, {'Р', 0.048}, {'С', 0.054}, {'Т', 0.064}, {'У', 0.026}, {'Ф', 0.002}, {'Х', 0.009}, {'Ц', 0.004},
{'Ч', 0.014}, {'Ш', 0.007}, {'Щ', 0.003}, {'Ъ', 0.014}, {'Ы', 0.019}, {'Ь', 0.017}, {'Э', 0.003}, {'Ю', 0.006}, {'Я', 0.020}
};
for (size_t i = 0; i < 8 && i < sorted_key_lengths.size(); ++i) {
int key_length = sorted_key_lengths[i].first;
std::string key = find_key(input_text, key_length, russian_frequencies);
std::cout << "Длина ключа: " << key_length << "\n";
std::cout << "Найденный ключ: " << key << "\n";
std::string decrypted_text = vigenere_decrypt(input_text, key);
std::cout << "Расшифрованный текст:\n" << decrypted_text << "\n\n";
}
return 0;
Код 4:
#include
#include
#include
#include
#include
#include
std::string vigenere_encrypt(const std::string& plain_text, const std::string& key) {
std::string encrypted_text;
int key_length = key.length();
std::string upper_key = key;
std::transform(upper_key.begin(), upper_key.end(), upper_key.begin(), ::toupper);
std::string alphabet = "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
for (size_t i = 0; i < plain_text.length(); ++i) {
char char_upper = std::toupper(plain_text[i]);
size_t pos = alphabet.find(char_upper);
if (pos != std::string::npos) {
char key_char = upper_key[i % key_length];
size_t shift = alphabet.find(key_char);
size_t encrypted_pos = (pos + shift) % alphabet.length();
char encrypted_char = alphabet[encrypted_pos];
if (std::islower(plain_text[i])) {
encrypted_char = std::tolower(encrypted_char);
}
encrypted_text.push_back(encrypted_char);
} else {
encrypted_text.push_back(plain_text[i]);
}
}
return encrypted_text;
std::string clean_key(const std::string& key) {
std::string cleaned_key;
for (char c : key) {
if ((c >= 'А' && c <= 'Я') || (c >= 'а' && c <= 'я')) {
cleaned_key.push_back(c);
}
}
return cleaned_key;
}
std::string read_file(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Ошибка: файл " << filename << " не может быть открыт.\n";
exit(1);
}
std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator());
file.close();
return content;
}
void write_file(const std::string& filename, const std::string& content) {
std::ofstream file(filename);
if (!file.is_open()) {
std::cerr << "Ошибка: файл " << filename << " не может быть открыт для записи.\n";
exit(1);
}
file << content;
file.close();
}
std::string prepare_text(const std::string& text) {
std::string prepared_text;
for (char c : text) {
if (c >= 'А' && c <= 'Я') {
prepared_text.push_back(c);
}
}
return prepared_text;
}
int main() {
std::string key = read_file("C:\Users\user\documents\key.txt");
key = clean_key(key);
if (key.empty()) {
std::cerr << "Ошибка: ключ не может быть пустым после удаления лишних символов.\n";
return 1;
}
std::string input_text = read_file("C:\\Users\\user\\documents\\rus_text_input.txt");
std::string plain_text = prepare_text(input_text);
std::string encrypted_text = vigenere_encrypt(plain_text, key);
std::cout << "Ключ: " << key << "\n";
std::cout << "Зашифрованный текст: " << encrypted_text << "\n";
write_file("rus_text_encrypted.txt", encrypted_text);
return 0;
И сделай так, чтобы вручную выбирать путь к файлам в окошке, если это взможно
Давайте объединим все предоставленные коды, добавим выбор шифрования/расшифрования, выбор английского/русского алфавита и обеспечим возможность выбора пути к файлам с помощью диалогового окна.
Мы будем использовать библиотеку <filesystem> для работы с файлами и <string_view> для упрощения работы с строками. Также для простоты взаимодействия с пользователем сделаем консольное меню.
Вот объединённый код:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <stdexcept>
std::string vigenere_decrypt(const std::string& ciphertext, const std::string& key, bool is_russian) {
std::string decrypted_text;
int key_length = key.length();
std::string upper_key = key;
std::transform(upper_key.begin(), upper_key.end(), upper_key.begin(), ::toupper);
for (size_t i = 0; i < ciphertext.length(); ++i) {
char char_upper = std::toupper(ciphertext[i]);
if (is_russian ? (char_upper >= 'А' && char_upper <= 'Я') : (char_upper >= 'A' && char_upper <= 'Z')) {
char key_char = upper_key[i % key_length];
int key_shift = is_russian ? (key_char - 'А') : (key_char - 'A');
char decrypted_char = is_russian ? (char_upper - 'А' - key_shift + 32) % 32 + 'А' : ((char_upper - 'A' - key_shift + 26) % 26 + 'A');
decrypted_text.push_back(decrypted_char);
} else {
decrypted_text.push_back(ciphertext[i]);
}
}
return decrypted_text;
}
std::string vigenere_encrypt(const std::string& plain_text, const std::string& key, bool is_russian) {
std::string encrypted_text;
int key_length = key.length();
std::string upper_key = key;
std::transform(upper_key.begin(), upper_key.end(), upper_key.begin(), ::toupper);
std::string alphabet = is_russian ? "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ" : "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (size_t i = 0; i < plain_text.length(); ++i) {
char char_upper = std::toupper(plain_text[i]);
size_t pos = alphabet.find(char_upper);
if (pos != std::string::npos) {
char key_char = upper_key[i % key_length];
size_t shift = alphabet.find(std::toupper(key_char));
size_t encrypted_pos = (pos + shift) % alphabet.length();
char encrypted_char = alphabet[encrypted_pos];
if (std::islower(plain_text[i])) {
encrypted_char = std::tolower(encrypted_char);
}
encrypted_text.push_back(encrypted_char);
} else {
encrypted_text.push_back(plain_text[i]);
}
}
return encrypted_text;
}
std::string read_file(const std::string& filename) {
if (!std::filesystem::exists(filename)) {
throw std::runtime_error("Ошибка: файл не может быть открыт.");
}
std::ifstream file(filename);
std::string content((std::istreambuf_iterator<char>(file)), (std::istreambuf_iterator<char>()));
return content;
}
void write_file(const std::string& filename, const std::string& content) {
std::ofstream file(filename);
file << content;
}
std::string clean_key(const std::string& key) {
std::string cleaned_key;
for (char c : key) {
if ((c >= 'А' && c <= 'Я') || (c >= 'а' && c <= 'я') || (c >= 'A' && c <= 'Z')) {
cleaned_key.push_back(c);
}
}
return cleaned_key;
}
std::string prepare_text(const std::string& text, bool is_russian) {
std::string prepared_text;
for (char c : text) {
if ((is_russian && c >= 'А' && c <= 'Я') || (!is_russian && c >= 'A' && c <= 'Z')) {
prepared_text.push_back(std::toupper(c));
}
}
return prepared_text;
}
std::string get_file_path() {
std::string path;
std::cout << "Введите путь к файлу: ";
std::getline(std::cin, path);
return path;
}
int main() {
int choice;
std::cout << "Выберите опцию:\n1. Зашифровать текст\n2. Расшифровать текст\n";
std::cin >> choice;
std::cin.ignore(); // Сбрасываем буфер ввода после выбора
bool is_russian;
std::cout << "Выберите язык:\n1. Русский\n2. Английский\n";
std::cin >> is_russian;
std::cin.ignore(); // Сбрасываем буфер ввода после выбора
std::string key_file = get_file_path();
std::string key = read_file(key_file);
key = clean_key(key);
if (key.empty()) {
std::cerr << "Ошибка: ключ не может быть пустым.\n";
return 1;
}
std::string input_file = get_file_path();
std::string input_text = read_file(input_file);
std::string prepared_text = prepare_text(input_text, is_russian);
std::string output_text;
if (choice == 1) {
output_text = vigenere_encrypt(prepared_text, key, is_russian);
} else if (choice == 2) {
output_text = vigenere_decrypt(prepared_text, key, is_russian);
}
std::string output_file;
std::cout << "Введите путь для сохранения файла: ";
std::getline(std::cin, output_file);
write_file(output_file, output_text);
std::cout << "Готово!\n";
return 0;
}
Объяснение изменений:
Функции Шифрования и Расшифрования : Объединены функции шифрования и расшифрования для русского и английского алфавитов.
Чтение и Запись Файлов : Добавлены функции read_file и write_file для работы с файлами. Проверяется, существует ли файл, перед его чтением.
Очистка Ключа : Функция clean_key очистит ключ от недопустимых символов.
Подготовка Текста : Функция prepare_text подготавливает текст для шифрования, убирая все символы, не относящиеся к выбранному алфавиту.
Выбор Путей К Файлам : Введена функция get_file_path для получения путей к файлам через консольный ввод.
Пользовательский Интерфейс : Консольное меню позволяет выбрать тип операции (шифрование или расшифрование) и язык.
Как использовать:
Скомпилируйте код в среде C++ с поддержкой C++17.
Запустите программу и следуйте инструкциям в консоли для шифрования или расшифрования текста, вводя необходимые пути к файлам.
Copy first response
Not yet included in a published release.