Перепиши данный код на java def vigenereencrypt(text, key, alphabet): encrypted = []…
- User
Перепиши данный код на java def vigenere_encrypt(text, key, alphabet): encrypted = [] key_indices = [] n = len(alphabet)
for k in key: if k.lower() in alphabet: key_indices.append(alphabet.index(k.lower())) key_length = len(key_indices) if key_length == 0: print("Ключ не содержит символов из выбранного алфавита.") return None for i, char in enumerate(text): if char.lower() in alphabet: is_upper = char.isupper() idx = alphabet.index(char.lower()) shift = key_indices[i % key_length] encrypted_idx = (idx + shift) % n encrypted_char = alphabet[encrypted_idx] if is_upper: encrypted_char = encrypted_char.upper() encrypted.append(encrypted_char) else: encrypted.append(char) return ''.join(encrypted)def vigenere_decrypt(text, key, alphabet): decrypted = [] key_indices = [] n = len(alphabet)
for k in key: if k.lower() in alphabet: key_indices.append(alphabet.index(k.lower())) key_length = len(key_indices) if key_length == 0: print("Ключ не содержит символов из выбранного алфавита.") return None for i, char in enumerate(text): if char.lower() in alphabet: is_upper = char.isupper() idx = alphabet.index(char.lower()) shift = key_indices[i % key_length] decrypted_idx = (idx - shift) % n decrypted_char = alphabet[decrypted_idx] if is_upper: decrypted_char = decrypted_char.upper() decrypted.append(decrypted_char) else: decrypted.append(char) return ''.join(decrypted)def combine_keys(key1, key2, alphabet): from math import lcm key1_indices = [] key2_indices = [] n = len(alphabet)
for k in key1: if k.lower() in alphabet: key1_indices.append(alphabet.index(k.lower())) for k in key2: if k.lower() in alphabet: key2_indices.append(alphabet.index(k.lower())) key1_length = len(key1_indices) key2_length = len(key2_indices) if key1_length == 0 or key2_length == 0: print("Один из ключей не содержит символов из выбранного алфавита.") return None key_length = lcm(key1_length, key2_length) combined_key = '' for i in range(key_length): shift1 = key1_indices[i % key1_length] shift2 = key2_indices[i % key2_length] combined_shift = (shift1 + shift2) % n combined_char = alphabet[combined_shift] combined_key += combined_char return combined_keydef main(): import sys
print("Выберите алфавит:") print("1. Русский") print("2. Английский") choice = input("Введите номер алфавита (1 или 2): ") if choice == '1': alphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя' elif choice == '2': alphabet = 'abcdefghijklmnopqrstuvwxyz' else: print("Неверный выбор алфавита.") sys.exit() n = len(alphabet) file_path = input("Введите путь к файлу с исходным текстом (.txt): ") try: with open(file_path, 'r', encoding='utf-8') as f: original_text = f.read() except FileNotFoundError: print("Файл не найден. Проверьте путь и повторите попытку.") sys.exit() key1_path = input("Введите путь к файлу с первым ключом K1 (.txt): ") try: with open(key1_path, 'r', encoding='utf-8') as f: key1 = f.read().strip() except FileNotFoundError: print("Файл с первым ключом не найден. Проверьте путь и повторите попытку.") sys.exit() key2_path = input("Введите путь к файлу со вторым ключом K2 (.txt): ") try: with open(key2_path, 'r', encoding='utf-8') as f: key2 = f.read().strip() except FileNotFoundError: print("Файл со вторым ключом не найден. Проверьте путь и повторите попытку.") sys.exit() ciphertext1 = vigenere_encrypt(original_text, key1, alphabet) if ciphertext1 is None: print("\nПроизошла ошибка при шифровании текста с помощью первого ключа.") sys.exit() ciphertext2 = vigenere_encrypt(ciphertext1, key2, alphabet) if ciphertext2 is None: print("\nПроизошла ошибка при шифровании текста с помощью второго ключа.") sys.exit() combined_key = combine_keys(key1, key2, alphabet) if combined_key is None: print("\nПроизошла ошибка при составлении комбинированного ключа.") sys.exit() ciphertext_combined = vigenere_encrypt(original_text, combined_key, alphabet) if ciphertext_combined is None: print("\nПроизошла ошибка при шифровании с помощью комбинированного ключа.") sys.exit() key1_filtered = ''.join([char for char in key1 if char.lower() in alphabet]) key2_filtered = ''.join([char for char in key2 if char.lower() in alphabet]) print("\n------------------------------------") print("\033[1;3mПервый ключ:\033[0m") print(key1_filtered) print("\033[1;3mШифротекст после первого шифрования:\033[0m") print(ciphertext1) print("\n------------------------------------") print("\033[1;3mВторой ключ:\033[0m") print(key2_filtered) print("\033[1;3mШифротекст после второго шифрования:\033[0m") print(ciphertext2) print("\n------------------------------------") print("\033[1;3mКомбинированный ключ:\033[0m") print(combined_key) print("\033[1;3mШифротекст после шифрования с комбинированным ключом:\033[0m") # print("\nШифротекст после шифрования с комбинированным ключом:") print(ciphertext_combined) print("\n------------------------------------") with open('output.txt', 'w', encoding='utf-8') as f: f.write(ciphertext_combined) with open('key3.txt', 'w', encoding='utf-8') as f: f.write(combined_key) print("\nШифротекст сохранён в файле 'output.txt'.") print("Комбинированный ключ сохранён в файле 'key3.txt'.") decrypted_text = vigenere_decrypt(ciphertext_combined, combined_key, alphabet) if decrypted_text is None: print("\nПроизошла ошибка при дешифровании текста.") sys.exit() print("\nДешифрованный текст:") print(decrypted_text) if ciphertext2 == ciphertext_combined: print("\nШифротексты совпадают. Комбинированный ключ работает корректно.") else: print("\nШифротексты не совпадают. Проверьте реализацию.") if decrypted_text == original_text: print("Дешифрование успешно. Исходный текст восстановлен.") else: print("Дешифрование некорректно. Проверьте реализацию.")if name == "main": main()
- Assistant
Вот переписанный код на Java, который соответствует вашему Python коду для шифрования и дешифрования с использованием шифра Виженера:
import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class VigenereCipher { public static String vigenereEncrypt(String text, String key, String alphabet) { StringBuilder encrypted = new StringBuilder(); List<Integer> keyIndices = new ArrayList<>(); int n = alphabet.length(); for (char k : key.toCharArray()) { int index = alphabet.indexOf(Character.toLowerCase(k)); if (index >= 0) { keyIndices.add(index); } } int keyLength = keyIndices.size(); if (keyLength == 0) { System.out.println("Ключ не содержит символов из выбранного алфавита."); return null; } for (int i = 0; i < text.length(); i++) { char charAt = text.charAt(i); if (alphabet.indexOf(Character.toLowerCase(charAt)) >= 0) { boolean isUpper = Character.isUpperCase(charAt); int idx = alphabet.indexOf(Character.toLowerCase(charAt)); int shift = keyIndices.get(i % keyLength); int encryptedIdx = (idx + shift) % n; char encryptedChar = alphabet.charAt(encryptedIdx); encrypted.append(isUpper ? Character.toUpperCase(encryptedChar) : encryptedChar); } else { encrypted.append(charAt); } } return encrypted.toString(); } public static String vigenereDecrypt(String text, String key, String alphabet) { StringBuilder decrypted = new StringBuilder(); List<Integer> keyIndices = new ArrayList<>(); int n = alphabet.length(); for (char k : key.toCharArray()) { int index = alphabet.indexOf(Character.toLowerCase(k)); if (index >= 0) { keyIndices.add(index); } } int keyLength = keyIndices.size(); if (keyLength == 0) { System.out.println("Ключ не содержит символов из выбранного алфавита."); return null; } for (int i = 0; i < text.length(); i++) { char charAt = text.charAt(i); if (alphabet.indexOf(Character.toLowerCase(charAt)) >= 0) { boolean isUpper = Character.isUpperCase(charAt); int idx = alphabet.indexOf(Character.toLowerCase(charAt)); int shift = keyIndices.get(i % keyLength); int decryptedIdx = (idx - shift + n) % n; // Добавляем n для обработки отрицательных индексов char decryptedChar = alphabet.charAt(decryptedIdx); decrypted.append(isUpper ? Character.toUpperCase(decryptedChar) : decryptedChar); } else { decrypted.append(charAt); } } return decrypted.toString(); } public static String combineKeys(String key1, String key2, String alphabet) { List<Integer> key1Indices = new ArrayList<>(); List<Integer> key2Indices = new ArrayList<>(); int n = alphabet.length(); for (char k : key1.toCharArray()) { int index = alphabet.indexOf(Character.toLowerCase(k)); if (index >= 0) { key1Indices.add(index); } } for (char k : key2.toCharArray()) { int index = alphabet.indexOf(Character.toLowerCase(k)); if (index >= 0) { key2Indices.add(index); } } int key1Length = key1Indices.size(); int key2Length = key2Indices.size(); if (key1Length == 0 || key2Length == 0) { System.out.println("Один из ключей не содержит символов из выбранного алфавита."); return null; } int lcm = lcm(key1Length, key2Length); StringBuilder combinedKey = new StringBuilder(); for (int i = 0; i < lcm; i++) { int shift1 = key1Indices.get(i % key1Length); int shift2 = key2Indices.get(i % key2Length); int combinedShift = (shift1 + shift2) % n; combinedKey.append(alphabet.charAt(combinedShift)); } return combinedKey.toString(); } private static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } private static int lcm(int a, int b) { return a * (b / gcd(a, b)); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String alphabet; System.out.println("Выберите алфавит:"); System.out.println("1. Русский"); System.out.println("2. Английский"); System.out.print("Введите номер алфавита (1 или 2): "); String choice = scanner.nextLine(); if (choice.equals("1")) { alphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; } else if (choice.equals("2")) { alphabet = "abcdefghijklmnopqrstuvwxyz"; } else { System.out.println("Неверный выбор алфавита."); return; } System.out.print("Введите путь к файлу с исходным текстом (.txt): "); String filePath = scanner.nextLine(); String originalText = readFile(filePath); System.out.print("Введите путь к файлу с первым ключом K1 (.txt): "); String key1Path = scanner.nextLine(); String key1 = readFile(key1Path).trim(); System.out.print("Введите путь к файлу со вторым ключом K2 (.txt): "); String key2Path = scanner.nextLine(); String key2 = readFile(key2Path).trim(); String ciphertext1 = vigenereEncrypt(originalText, key1, alphabet); if (ciphertext1 == null) return; String ciphertext2 = vigenereEncrypt(ciphertext1, key2, alphabet); if (ciphertext2 == null) return; String combinedKey = combineKeys(key1, key2, alphabet); if (combinedKey == null) return; String ciphertextCombined = vigenereEncrypt(originalText, combinedKey, alphabet); if (ciphertextCombined == null) return; String key1Filtered = filterKey(key1, alphabet); String key2Filtered = filterKey(key2, alphabet); System.out.println("\n------------------------------------"); System.out.println("Первый ключ:"); System.out.println(key1Filtered); System.out.println("Шифротекст после первого шифрования:"); System.out.println(ciphertext1); System.out.println("\n------------------------------------"); System.out.println("Второй ключ:"); System.out.println(key2Filtered); System.out.println("Шифротекст после второго шифрования:"); System.out.println(ciphertext2); System.out.println("\n------------------------------------"); System.out.println("Комбинированный ключ:"); System.out.println(combinedKey); System.out.println("Шифротекст после шифрования с комбинированным ключом:"); System.out.println(ciphertextCombined); System.out.println("\n------------------------------------"); writeFile("output.txt", ciphertextCombined); writeFile("key3.txt", combinedKey); System.out.println("\nШифротекст сохранён в файле 'output.txt'."); System.out.println("Комбинированный ключ сохранён в файле 'key3.txt'."); String decryptedText = vigenereDecrypt(ciphertextCombined, combinedKey, alphabet); if (decryptedText == null) return; System.out.println("\nДешифрованный текст:"); System.out.println(decryptedText); if (ciphertext2.equals(ciphertextCombined)) { System.out.println("\nШифротексты совпадают. Комбинированный ключ работает корректно."); } else { System.out.println("\nШифротексты не совпадают. Проверьте реализацию."); } if (decryptedText.equals(originalText)) { System.out.println("Дешифрование успешно. Исходный текст восстановлен."); } else { System.out.println("Дешифрование некорректно. Проверьте реализацию."); } } private static String readFile(String path) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8))) { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } return content.toString().trim(); } catch (IOException e) { System.out.printf("Файл '%s' не найден. Проверьте путь и повторите попытку.%n", path); System.exit(1); return null; } } private static void writeFile(String path, String content) { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8))) { writer.write(content); } catch (IOException e) { System.out.printf("Ошибка при записи в файл '%s'.%n", path); System.exit(1); } } private static String filterKey(String key, String alphabet) { StringBuilder filtered = new StringBuilder(); for (char c : key.toCharArray()) { if (alphabet.indexOf(Character.toLowerCase(c)) >= 0) { filtered.append(c); } } return filtered.toString(); } }Объяснение кода:
-
Методы VigenereEncrypt и VigenereDecrypt: Шифруют и дешифруют текст с использованием предоставленного ключа и алфавита. Они учитывают регистр символов и игнорируют символы, которые не входят в алфавит.
-
Метод CombineKeys: Объединяет два ключа, чтобы создать комбинированный ключ для шифрования.
-
GCD и LCM: Методы для нахождения наибольшего общего делителя и наименьшего общего кратного, используемые в
combineKeys. -
Чтение и запись файлов: Используются методы
readFileиwriteFileдля работы с текстовыми файлами, чтобы считывать исходный текст и сохранять шифротекст и ключи. -
Фильтрация ключа: Метод
filterKeyдля фильтрации символов ключа, которые не содержатся в заданном алфавите.
Этот код следует логике исходного Python кода и должен выполнять те же задачи. Обязательно протестируйте его в вашей среде, чтобы убедиться в корректности выполнения.
-