Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions META-INF/MANIFEST.MF
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Manifest-Version: 1.0
Main-Class: ua.com.javarush.gnew.Main

Binary file added out/artifacts/GNEW_M1_FP_jar/GNEW-M1-FP.jar
Binary file not shown.
43 changes: 23 additions & 20 deletions readme.md
Original file line number Diff line number Diff line change
@@ -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
```

- -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

107 changes: 107 additions & 0 deletions src/main/java/ua/com/javarush/gnew/CLI/CryptAnalyzerGUI.java
Original file line number Diff line number Diff line change
@@ -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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very good job here.

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<String> 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);
}
}

42 changes: 42 additions & 0 deletions src/main/java/ua/com/javarush/gnew/Constants/Constants.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package ua.com.javarush.gnew.Constants;

import java.util.ArrayList;
import java.util.Arrays;

public class Constants {
private static ArrayList<Character> 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<Character> 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<Character> UKR_LOWER = new ArrayList<>(Arrays.asList(
'а', 'б', 'в', 'г', 'ґ', 'д', 'е', 'є', 'ж', 'з', 'и', 'і', 'ї', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ь', 'ю', 'я'));
private static ArrayList<Character> UKR_UPPER = new ArrayList<>(Arrays.asList(
'А', 'Б', 'В', 'Г', 'Ґ', 'Д', 'Е', 'Є', 'Ж', 'З', 'И', 'І', 'Ї', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ь', 'Ю', 'Я'));

public ArrayList<Character> getEngLower(){
return ENG_LOWER;
}
public void setEngLower(ArrayList<Character> ENG_LOWER){
Constants.ENG_LOWER = ENG_LOWER;
}
public ArrayList<Character> getEngUpper(){
return ENG_UPPER;
}
public void setEngUpper(ArrayList<Character> ENG_UPPER){
Constants.ENG_UPPER = ENG_UPPER;
}
public ArrayList<Character> getUkrLower(){
return UKR_LOWER;
}
public void setUkrLower(ArrayList<Character> UKR_LOWER){
Constants.UKR_LOWER = UKR_LOWER;
}
public ArrayList<Character> getUkrUpper(){
return UKR_UPPER;
}
public void setUkrUpper(ArrayList<Character> UKR_UPPER){
Constants.UKR_UPPER = UKR_UPPER;
}
}


27 changes: 27 additions & 0 deletions src/main/java/ua/com/javarush/gnew/Dictionary/Dictionary.java
Original file line number Diff line number Diff line change
@@ -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;
}
}


37 changes: 30 additions & 7 deletions src/main/java/ua/com/javarush/gnew/Main.java
Original file line number Diff line number Diff line change
@@ -1,32 +1,55 @@
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;
import ua.com.javarush.gnew.runner.RunOptions;

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");
}
}
Comment on lines 24 to 54
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code looks complicated and contains duplicates.
Could be simplified. See more here.

}
}
75 changes: 75 additions & 0 deletions src/main/java/ua/com/javarush/gnew/crypt/code/Cryptanalyzer.java
Original file line number Diff line number Diff line change
@@ -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<Character> ENG_LOWER_MOD = new ArrayList<>(constants.getEngLower());
ArrayList<Character> UKR_LOWER_MOD = new ArrayList<>(constants.getUkrLower());
Collections.rotate(ENG_LOWER_MOD, key);
Collections.rotate(UKR_LOWER_MOD, key);

ArrayList<Character> ENG_UPPER_MOD = new ArrayList<>(constants.getEngUpper());
ArrayList<Character> 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();
Comment on lines +27 to +63
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Too complicated and hard to read / change. Might be simplified by extracting methods. See more here.

}

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);
}
}
Loading