diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF new file mode 100644 index 0000000..e523bee --- /dev/null +++ b/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Main-Class: ua.com.javarush.gnew.Main + diff --git a/out/artifacts/GNEW_M1_FP_jar/GNEW-M1-FP.jar b/out/artifacts/GNEW_M1_FP_jar/GNEW-M1-FP.jar new file mode 100644 index 0000000..ce960e3 Binary files /dev/null and b/out/artifacts/GNEW_M1_FP_jar/GNEW-M1-FP.jar differ diff --git a/readme.md b/readme.md index a17a9ac..586b8e4 100644 --- a/readme.md +++ b/readme.md @@ -1,28 +1,31 @@ +### Notes: +- This Cypher can ENCRYPT or DECRYPT your sentences. +- You can found correct texts or sentences by using this program. +- You can decrypt or encrypt text by using CESAR CYPHER. +- Support for UKRAINIAN and ENGLISH languages in encryption, decryption, and also in brute force -## Run the program +### Last Upgrades: +- We have an automatic program that can obtain decrypted text without a key. +- The program now takes into account spaces in the specified parameters. +- Some bug fixed. + +### Brute force +- Сan automatically decrypt any text (Caesar cipher) and find the correct key. ### Commands: -``` --e Encrypt --d Decrypt --bf Brute force -``` +- -e Encrypt +- -d Decrypt +- -bf Brute force ### Arguments: -``` --k Key --f File path -``` + +- You need to write the arguments in the order: encrypt/decrypt/bruteforce(e,d,bf) + key(1 or -1 and further in decreasing, increasing order) + file path. + In the case of bruteforce, a key is not needed. ### Example: -``` --e -k 1 -f "/path/to/file.txt" - Encrypt file with key 1 --d -k 5 -f "/path/to/file [ENCRYPTED].txt" - Decrypt file with key 5 --bf -f "/path/to/file [ENCRYPTED].txt" - Brute force decrypt file -``` - -### Argument could be in any order -``` --e -f "/path/to/file.txt" -k 1 -``` \ No newline at end of file + +- -e -k 1 -f "/path/to/file.txt" - Encrypt file with key 1 +- -d -k 5 -f "/path/to/file [ENCRYPTED].txt" - Decrypt file with key 5 +- -bf -f "/path/to/file [ENCRYPTED].txt" - Brute force decrypt file + diff --git a/src/main/java/ua/com/javarush/gnew/CLI/CryptAnalyzerGUI.java b/src/main/java/ua/com/javarush/gnew/CLI/CryptAnalyzerGUI.java new file mode 100644 index 0000000..237f7ca --- /dev/null +++ b/src/main/java/ua/com/javarush/gnew/CLI/CryptAnalyzerGUI.java @@ -0,0 +1,107 @@ +package ua.com.javarush.gnew.CLI; + +import ua.com.javarush.gnew.Dictionary.Dictionary; +import ua.com.javarush.gnew.crypt.code.Cryptanalyzer; +import ua.com.javarush.gnew.crypt.code.RunBruteforce; +import ua.com.javarush.gnew.file.FileManager; +import ua.com.javarush.gnew.runner.Command; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.io.IOException; +import java.nio.file.Path; + +public class CryptAnalyzerGUI { + private static final Cryptanalyzer cryptanalyzer = new Cryptanalyzer(); + private static final RunBruteforce runBruteforce = new RunBruteforce(); + private static final FileManager fileManager = new FileManager(); + private static final Dictionary dictionary = new Dictionary(); + + public static void main(String[] args) { + JFrame frame = new JFrame("Cryptanalyzer"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(500, 400); + + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + + JLabel commandLabel = new JLabel("Выберите команду:"); + panel.add(commandLabel); + + String[] commands = {"ENCRYPT", "DECRYPT", "BRUTEFORCE"}; + JComboBox commandBox = new JComboBox<>(commands); + panel.add(commandBox); + + JLabel fileLabel = new JLabel("Выберите файл:"); + JTextField filePathField = new JTextField(20); + JButton fileButton = new JButton("Выбрать файл"); + fileButton.addActionListener(e -> { + JFileChooser fileChooser = new JFileChooser(); + int returnValue = fileChooser.showOpenDialog(null); + if (returnValue == JFileChooser.APPROVE_OPTION) { + filePathField.setText(fileChooser.getSelectedFile().getPath()); + } + }); + + JPanel filePanel = new JPanel(); + filePanel.add(filePathField); + filePanel.add(fileButton); + panel.add(fileLabel); + panel.add(filePanel); + + JLabel keyLabel = new JLabel("Введите ключ (только для ENCRYPT и DECRYPT):"); + JTextField keyField = new JTextField(10); + panel.add(keyLabel); + panel.add(keyField); + + JButton executeButton = new JButton("Выполнить"); + panel.add(executeButton); + + JTextArea resultArea = new JTextArea(10, 30); + resultArea.setEditable(false); + JScrollPane scrollPane = new JScrollPane(resultArea); + panel.add(scrollPane); + + executeButton.addActionListener((ActionEvent e) -> { + try { + String selectedCommand = (String) commandBox.getSelectedItem(); + Path filePath = Path.of(filePathField.getText()); + String content = fileManager.read(filePath); + + if (selectedCommand.equals("ENCRYPT")) { + int key = Integer.parseInt(keyField.getText()); + String encryptedContent = cryptanalyzer.encryption(content, key); + String newFileName = filePath.getFileName().toString().replace(".txt", " [ENCRYPTED].txt"); + Path newFilePath = filePath.resolveSibling(newFileName); + fileManager.write(newFilePath, encryptedContent); + resultArea.setText("Файл успешно зашифрован: " + newFilePath); + } else if (selectedCommand.equals("DECRYPT")) { + int key = Integer.parseInt(keyField.getText()); + String decryptedContent = cryptanalyzer.decryption(content, key); + String newFileName = filePath.getFileName().toString().replace(".txt", " [DECRYPTED].txt"); + Path newFilePath = filePath.resolveSibling(newFileName); + fileManager.write(newFilePath, decryptedContent); + resultArea.setText("Файл успешно расшифрован: " + newFilePath); + } else if (selectedCommand.equals("BRUTEFORCE")) { + String decryptedContent = runBruteforce.bruteforce(content, dictionary.getDictionary(), dictionary.getDictionaryUKR()); + String key = runBruteforce.getKey(content, dictionary.getDictionary(), dictionary.getDictionaryUKR()).replace("Key: ", ""); + String newFileName = filePath.getFileName().toString().replace(".txt", " [DECRYPTED Key-" + key + "].txt"); + Path newFilePath = filePath.resolveSibling(newFileName); + fileManager.write(newFilePath, decryptedContent); + resultArea.setText("Брутфорс выполнен. Найден ключ: " + key + "\nФайл сохранен как: " + newFilePath); + } + } catch (IOException ex) { + resultArea.setText("Ошибка чтения/записи файла: " + ex.getMessage()); + } catch (NumberFormatException ex) { + resultArea.setText("Неправильный формат ключа: " + ex.getMessage()); + } catch (Exception ex) { + resultArea.setText("Произошла ошибка: " + ex.getMessage()); + } + }); + + frame.add(panel); + frame.setVisible(true); + } +} + diff --git a/src/main/java/ua/com/javarush/gnew/Constants/Constants.java b/src/main/java/ua/com/javarush/gnew/Constants/Constants.java new file mode 100644 index 0000000..0e364a9 --- /dev/null +++ b/src/main/java/ua/com/javarush/gnew/Constants/Constants.java @@ -0,0 +1,42 @@ +package ua.com.javarush.gnew.Constants; + +import java.util.ArrayList; +import java.util.Arrays; + + public class Constants { + private static ArrayList ENG_LOWER = new ArrayList<>(Arrays.asList( + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')); + private static ArrayList ENG_UPPER = new ArrayList<>(Arrays.asList( + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z')); + private static ArrayList UKR_LOWER = new ArrayList<>(Arrays.asList( + 'а', 'б', 'в', 'г', 'ґ', 'д', 'е', 'є', 'ж', 'з', 'и', 'і', 'ї', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ь', 'ю', 'я')); + private static ArrayList UKR_UPPER = new ArrayList<>(Arrays.asList( + 'А', 'Б', 'В', 'Г', 'Ґ', 'Д', 'Е', 'Є', 'Ж', 'З', 'И', 'І', 'Ї', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ь', 'Ю', 'Я')); + + public ArrayList getEngLower(){ + return ENG_LOWER; + } + public void setEngLower(ArrayList ENG_LOWER){ + Constants.ENG_LOWER = ENG_LOWER; + } + public ArrayList getEngUpper(){ + return ENG_UPPER; + } + public void setEngUpper(ArrayList ENG_UPPER){ + Constants.ENG_UPPER = ENG_UPPER; + } + public ArrayList getUkrLower(){ + return UKR_LOWER; + } + public void setUkrLower(ArrayList UKR_LOWER){ + Constants.UKR_LOWER = UKR_LOWER; + } + public ArrayList getUkrUpper(){ + return UKR_UPPER; + } + public void setUkrUpper(ArrayList UKR_UPPER){ + Constants.UKR_UPPER = UKR_UPPER; + } + } + + diff --git a/src/main/java/ua/com/javarush/gnew/Dictionary/Dictionary.java b/src/main/java/ua/com/javarush/gnew/Dictionary/Dictionary.java new file mode 100644 index 0000000..c85b3f3 --- /dev/null +++ b/src/main/java/ua/com/javarush/gnew/Dictionary/Dictionary.java @@ -0,0 +1,27 @@ +package ua.com.javarush.gnew.Dictionary; + + + +public class Dictionary { + private static String[] dictionary = new String[]{"take", "or", "for", "of", "as", "his", "that", "he", "was", "for", "on", "are", "with", "they", "be", "at", "by", "word", "have", "play", "my", "world", "there", "those", "victory", "is", "not", "to", "in", "the"}; + + private static String[] dictionaryUKR = new String[]{"Ми", "всі", "щось", "Привіт", "хто", "що", "коли", "слово", "ти", "він", "вона", "воно", "вони", "йому", "робить", "працює", "каже", "розмовляє", "співає", "чує", "що робить", "збирає", "поле", "був", "була", "ні", "так", "тому що"}; + + public String[] getDictionary() { + return dictionary; + } + + public void setDictionary(String[] dictionary) { + Dictionary.dictionary = dictionary; + } + + public String[] getDictionaryUKR() { + return dictionaryUKR; + } + + public void setEngUpper(String[] dictionaryUKR) { + Dictionary.dictionaryUKR = dictionaryUKR; + } +} + + diff --git a/src/main/java/ua/com/javarush/gnew/Main.java b/src/main/java/ua/com/javarush/gnew/Main.java index 5906828..6254b44 100644 --- a/src/main/java/ua/com/javarush/gnew/Main.java +++ b/src/main/java/ua/com/javarush/gnew/Main.java @@ -1,6 +1,10 @@ package ua.com.javarush.gnew; -import ua.com.javarush.gnew.crypto.Cypher; + + +import ua.com.javarush.gnew.Dictionary.Dictionary; +import ua.com.javarush.gnew.crypt.code.Cryptanalyzer; +import ua.com.javarush.gnew.crypt.code.RunBruteforce; import ua.com.javarush.gnew.file.FileManager; import ua.com.javarush.gnew.runner.ArgumentsParser; import ua.com.javarush.gnew.runner.Command; @@ -8,25 +12,44 @@ import java.nio.file.Path; + public class Main { public static void main(String[] args) { - Cypher cypher = new Cypher(); + Cryptanalyzer cryptanalyzer = new Cryptanalyzer(); + RunBruteforce runBruteforce = new RunBruteforce(); FileManager fileManager = new FileManager(); ArgumentsParser argumentsParser = new ArgumentsParser(); RunOptions runOptions = argumentsParser.parse(args); - + Dictionary dictionary = new Dictionary(); try { if (runOptions.getCommand() == Command.ENCRYPT) { String content = fileManager.read(runOptions.getFilePath()); - String encryptedContent = cypher.encrypt(content, runOptions.getKey()); + String encryptedContent = cryptanalyzer.encryption(content, runOptions.getKey()); String fileName = runOptions.getFilePath().getFileName().toString(); String newFileName = fileName.substring(0, fileName.length() - 4) + " [ENCRYPTED].txt"; + Path newFilePath = runOptions.getFilePath().resolveSibling(newFileName); + fileManager.write(newFilePath, encryptedContent); + } else if (runOptions.getCommand() == Command.DECRYPT) { + String content = fileManager.read(runOptions.getFilePath()); + String encryptedContent = cryptanalyzer.decryption(content, runOptions.getKey()); + String fileName = runOptions.getFilePath().getFileName().toString(); + String newFileName = fileName.substring(0, fileName.length() - 4) + " [DECRYPTED].txt"; + + Path newFilePath = runOptions.getFilePath().resolveSibling(newFileName); + fileManager.write(newFilePath, encryptedContent); + } else if (runOptions.getCommand() == Command.BRUTEFORCE) { + String content = fileManager.read(runOptions.getFilePath()); + String encryptedContent = runBruteforce.bruteforce(content,dictionary.getDictionary(), dictionary.getDictionaryUKR()); + String fileName = runOptions.getFilePath().getFileName().toString(); + String key = runBruteforce.getKey(content, dictionary.getDictionary(), dictionary.getDictionaryUKR()).replace("Key: ", ""); + String newFileName = fileName.substring(0, fileName.length() - 4) + " [DECRYPTED Key -" + key + "].txt"; + Path newFilePath = runOptions.getFilePath().resolveSibling(newFileName); fileManager.write(newFilePath, encryptedContent); } - } catch (Exception e) { - System.out.println(e.getMessage()); + }catch (Exception e){ + System.out.println("Smth went wrong"); } } -} \ No newline at end of file +} diff --git a/src/main/java/ua/com/javarush/gnew/crypt/code/Cryptanalyzer.java b/src/main/java/ua/com/javarush/gnew/crypt/code/Cryptanalyzer.java new file mode 100644 index 0000000..e982eae --- /dev/null +++ b/src/main/java/ua/com/javarush/gnew/crypt/code/Cryptanalyzer.java @@ -0,0 +1,75 @@ +package ua.com.javarush.gnew.crypt.code; + +import ua.com.javarush.gnew.Constants.Constants; + +import java.util.ArrayList; +import java.util.Collections; + + + +public class Cryptanalyzer { + public String encryption(String str, int key) { + Constants constants = new Constants(); + key = Math.negateExact(key); + ArrayList ENG_LOWER_MOD = new ArrayList<>(constants.getEngLower()); + ArrayList UKR_LOWER_MOD = new ArrayList<>(constants.getUkrLower()); + Collections.rotate(ENG_LOWER_MOD, key); + Collections.rotate(UKR_LOWER_MOD, key); + + ArrayList ENG_UPPER_MOD = new ArrayList<>(constants.getEngUpper()); + ArrayList UKR_UPPER_MOD = new ArrayList<>(constants.getUkrUpper()); + Collections.rotate(ENG_UPPER_MOD, key); + Collections.rotate(UKR_UPPER_MOD, key); + + char[] array = str.toCharArray(); + StringBuilder builder = new StringBuilder(); + + for (char symbol : array) { + if (Character.isLowerCase(symbol)) { + int originalIndex = constants.getEngLower().indexOf(symbol); + if (originalIndex != -1) { + Character encrypted = ENG_LOWER_MOD.get(originalIndex); + builder.append(encrypted); + continue; + } + + originalIndex = constants.getUkrLower().indexOf(symbol); + if (originalIndex != -1) { + Character encrypted = UKR_LOWER_MOD.get(originalIndex); + builder.append(encrypted); + } else { + builder.append(symbol); + } + } + else if (Character.isUpperCase(symbol)) { + int originalIndex = constants.getEngUpper().indexOf(symbol); + if (originalIndex != -1) { + Character encrypted = ENG_UPPER_MOD.get(originalIndex); + builder.append(encrypted); + continue; + } + + originalIndex = constants.getUkrUpper().indexOf(symbol); + if (originalIndex != -1) { + Character encrypted = UKR_UPPER_MOD.get(originalIndex); + builder.append(encrypted); + } else { + builder.append(symbol); + } + } else { + builder.append(symbol); + } + } + return builder.toString(); + } + + public String decryption(String str, int key) { + StringBuilder builder; + builder = new StringBuilder(encryption(str, -key)); + return builder.toString(); + } + + public String getDecryption(String str, int key){ + return decryption(str,key); + } +} diff --git a/src/main/java/ua/com/javarush/gnew/crypt/code/RunBruteforce.java b/src/main/java/ua/com/javarush/gnew/crypt/code/RunBruteforce.java new file mode 100644 index 0000000..63ca8b0 --- /dev/null +++ b/src/main/java/ua/com/javarush/gnew/crypt/code/RunBruteforce.java @@ -0,0 +1,83 @@ +package ua.com.javarush.gnew.crypt.code; + + +import ua.com.javarush.gnew.Constants.Constants; + + +public class RunBruteforce { + + public String bruteforce(String str, String[] dictionary, String[] dictionaryUKR) { + String bestMatch = null; + int maxMatches = 0; + StringBuilder builder; + Cryptanalyzer crypt = new Cryptanalyzer(); + Constants constants = new Constants(); + + for (int key = 0; key < constants.getEngLower().size(); key++) { + builder = new StringBuilder(crypt.getDecryption(str, key)); + String decryptedText = builder.toString(); + int matches = countMatches(decryptedText, dictionary); + + if (matches > maxMatches) { + maxMatches = matches; + bestMatch = decryptedText; + } + } + for (int key = 0; key <= constants.getUkrLower().size(); key++) { + builder = new StringBuilder(crypt.getDecryption(str, key)); + String decryptedText = builder.toString(); + int matches = countMatches(decryptedText, dictionaryUKR); + + if (matches > maxMatches) { + maxMatches = matches; + bestMatch = decryptedText; + } + } + + return bestMatch != null ? bestMatch : "Брутфорс не дал результатов."; + } + + private int countMatches(String text, String[] dictionary) { + int matches = 0; + for (String word : dictionary) { + if (text.contains(word)) { + matches++; + } + } + return matches; + } + + public String getKey(String str, String[] dictionary, String[] dictionaryUKR) { + int maxMatches = 0; + String keyResult = null; + StringBuilder builder; + Cryptanalyzer crypt = new Cryptanalyzer(); + Constants constants = new Constants(); + + for (int key = 0; key < constants.getEngLower().size(); key++) { + builder = new StringBuilder(crypt.getDecryption(str, key)); + String decryptedText = builder.toString(); + int matches = countMatches(decryptedText, dictionary); + + if (matches > maxMatches) { + maxMatches = matches; + keyResult = "Key: " + key + " (ENG)"; + } + } + + for (int key = 0; key < constants.getUkrLower().size(); key++) { + builder = new StringBuilder(crypt.getDecryption(str, key)); + String decryptedText = builder.toString(); + int matches = countMatches(decryptedText, dictionaryUKR); + + if (matches > maxMatches) { + maxMatches = matches; + keyResult = "Key: " + key + " (UKR)"; + } + } + return keyResult != null ? keyResult : "Ключ не найден."; + } +} + + + diff --git a/src/main/java/ua/com/javarush/gnew/crypto/Cypher.java b/src/main/java/ua/com/javarush/gnew/crypto/Cypher.java deleted file mode 100644 index 2b01247..0000000 --- a/src/main/java/ua/com/javarush/gnew/crypto/Cypher.java +++ /dev/null @@ -1,33 +0,0 @@ -package ua.com.javarush.gnew.crypto; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; - -public class Cypher { - private final ArrayList originalAlphabet = new ArrayList<>(Arrays.asList('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')); - - - public String encrypt(String input, int key) { - key = Math.negateExact(key); - - ArrayList rotatedAlphabet = new ArrayList<>(originalAlphabet); - Collections.rotate(rotatedAlphabet, key); - char[] charArray = input.toCharArray(); - - StringBuilder builder = new StringBuilder(); - for (char symbol : charArray) { - builder.append(processSymbol(symbol, rotatedAlphabet)); - } - return builder.toString(); - } - - private Character processSymbol(char symbol, ArrayList rotatedAlphabet) { - if (!originalAlphabet.contains(symbol)) { - return symbol; - } - int index = originalAlphabet.indexOf(symbol); - - return rotatedAlphabet.get(index); - } -} diff --git a/src/main/java/ua/com/javarush/gnew/file/FileManager.java b/src/main/java/ua/com/javarush/gnew/file/FileManager.java index d60744c..638f7c0 100644 --- a/src/main/java/ua/com/javarush/gnew/file/FileManager.java +++ b/src/main/java/ua/com/javarush/gnew/file/FileManager.java @@ -5,11 +5,11 @@ import java.nio.file.Path; public class FileManager { - public String read(Path filePath) throws IOException { - return Files.readString(filePath); + public String read(Path FilePath) throws IOException{ + return Files.readString(FilePath); } - public void write(Path filePath, String content) throws IOException { - Files.writeString(filePath, content); + public void write(Path FilePath, String content) throws IOException{ + Files.writeString(FilePath,content); } } diff --git a/src/main/java/ua/com/javarush/gnew/language/Language.java b/src/main/java/ua/com/javarush/gnew/language/Language.java deleted file mode 100644 index 067dd2f..0000000 --- a/src/main/java/ua/com/javarush/gnew/language/Language.java +++ /dev/null @@ -1,12 +0,0 @@ -package ua.com.javarush.gnew.language; - -import java.util.ArrayList; - -public abstract class Language { - - private final ArrayList alphabet; - - public Language(ArrayList alphabet) { - this.alphabet = alphabet; - } -} diff --git a/src/main/java/ua/com/javarush/gnew/runner/ArgumentsParser.java b/src/main/java/ua/com/javarush/gnew/runner/ArgumentsParser.java index eb42462..d255b75 100644 --- a/src/main/java/ua/com/javarush/gnew/runner/ArgumentsParser.java +++ b/src/main/java/ua/com/javarush/gnew/runner/ArgumentsParser.java @@ -2,6 +2,7 @@ import java.nio.file.Path; + public class ArgumentsParser { public RunOptions parse(String[] args) { Command command = null; @@ -11,52 +12,45 @@ public RunOptions parse(String[] args) { for (int i = 0; i < args.length; i++) { String arg = args[i]; - switch (arg) { - case "-e": - command = Command.ENCRYPT; - break; - - case "-d": - command = Command.DECRYPT; - break; - - case "-bf": - command = Command.BRUTEFORCE; - break; - case "-k": - if (i + 1 < args.length) { - key = Integer.parseInt(args[++i]); - } else { - throw new IllegalArgumentException("Missing value for key"); - } - break; - - case "-f": - if (i + 1 < args.length) { - filePath = Path.of(args[++i]); - } else { - throw new IllegalArgumentException("Missing value for file"); + if (arg.equalsIgnoreCase("-e")) { + command = Command.ENCRYPT; + } else if (arg.equalsIgnoreCase("-d")) { + command = Command.DECRYPT; + } else if (arg.equalsIgnoreCase("-bf")) { + command = Command.BRUTEFORCE; + } else if (arg.equalsIgnoreCase("-k")){ + if (i + 1 < args.length) { + key = Integer.parseInt(args[++i]); + } else { + throw new IllegalArgumentException("Missing value for key"); + } + }else if(arg.equalsIgnoreCase("-f")){ + if (i + 1 < args.length) { + StringBuilder filePathBuilder = new StringBuilder(args[++i]); + + while (i + 1 < args.length && !args[i + 1].startsWith("-")) { + filePathBuilder.append(" ").append(args[++i]); } - break; - - default: - throw new IllegalArgumentException("Unknown argument: " + arg); + filePath = Path.of(filePathBuilder.toString()); + } else { + throw new IllegalArgumentException("Missing value for file"); + } + } else { + throw new IllegalArgumentException("Unknown argument: " + arg); } } - if (command == null) { - throw new IllegalArgumentException("Command (-e, -d, or -bf) is required"); - } - if (key == null) { - throw new IllegalArgumentException("Key is required for encrypt or decrypt mode"); + if (command == Command.ENCRYPT || command == Command.DECRYPT) { + if (key == null) { + throw new IllegalArgumentException("Key is required for encrypt or decrypt mode"); + } } if (filePath == null) { throw new IllegalArgumentException("File path is required"); } - return new RunOptions(command, key, filePath); } - } + diff --git a/src/main/java/ua/com/javarush/gnew/runner/RunOptions.java b/src/main/java/ua/com/javarush/gnew/runner/RunOptions.java index 45e700b..5073768 100644 --- a/src/main/java/ua/com/javarush/gnew/runner/RunOptions.java +++ b/src/main/java/ua/com/javarush/gnew/runner/RunOptions.java @@ -3,28 +3,14 @@ import java.nio.file.Path; public class RunOptions { - /** - * Command to be executed. - * -e option for encryption. - * -d option for decryption. - * -b option for brute force. - */ + private final Command command; - /** - * Key to be used for encryption or decryption. - * For encryption mode, this is the shift value. - * -k option is required. - */ private final Integer key; - /** - * Path to the file to be processed. - * For encryption and decryption modes, this is the file to be encrypted or decrypted. - * -f option is required. - */ private final Path filePath; + public RunOptions(Command command, Integer key, Path filePath) { this.command = command; this.key = key; @@ -42,13 +28,4 @@ public Integer getKey() { public Path getFilePath() { return filePath; } - - @Override - public String toString() { - return "CommandOptions{" + - "command='" + command + '\'' + - ", key=" + key + - ", filePath=" + filePath + - '}'; - } } diff --git a/src/test/java/ua/com/javarush/gnew/MainTest.java b/src/test/java/ua/com/javarush/gnew/MainTest.java index b7f6356..89d57f6 100644 --- a/src/test/java/ua/com/javarush/gnew/MainTest.java +++ b/src/test/java/ua/com/javarush/gnew/MainTest.java @@ -15,7 +15,7 @@ import static org.junit.jupiter.api.Assertions.*; class MainTest { - private static final boolean UKRAINIAN_LANGUAGE_TEST = false; + private static final boolean UKRAINIAN_LANGUAGE_TEST = true; private static final String ENCRYPT_COMMAND = "-e"; private static final String DECRYPT_COMMAND = "-d"; private static final String BF_COMMAND = "-bf"; diff --git a/src/test/resources/test.txt b/src/test/resources/test.txt index 6769dd6..366d032 100644 --- a/src/test/resources/test.txt +++ b/src/test/resources/test.txt @@ -1 +1,38 @@ -Hello world! \ No newline at end of file +THE TRAGEDY OF HAMLET, PRINCE OF DENMARK + + + by William Shakespeare + + + + Dramatis Personae + + Claudius, King of Denmark. + Marcellus, Officer. + Hamlet, son to the former, and nephew to the present king. + Polonius, Lord Chamberlain. + Horatio, friend to Hamlet. + Laertes, son to Polonius. + Voltemand, courtier. + Cornelius, courtier. + Rosencrantz, courtier. + Guildenstern, courtier. + Osric, courtier. + A Gentleman, courtier. + A Priest. + Marcellus, officer. + Bernardo, officer. + Francisco, a soldier + Reynaldo, servant to Polonius. + Players. + Two Clowns, gravediggers. + Fortinbras, Prince of Norway. \s + A Norwegian Captain. + English Ambassadors. + + Getrude, Queen of Denmark, mother to Hamlet. + Ophelia, daughter to Polonius. + + Ghost of Hamlet's Father. + + Lords, ladies, Officers, Soldiers, Sailors, Messengers, Attendants.""" \ No newline at end of file