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

15 changes: 15 additions & 0 deletions inputData.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
The sun was setting over the quiet village,
casting a warm golden glow on the cobblestone streets.
Birds chirped softly, preparing for the night as the first stars appeared in the sky.
People were slowly closing their shops, exchanging friendly smiles and goodbyes.
Children played in the park, their laughter echoing through the air. In the distance,
the gentle sound of a river flowing added to the serene atmosphere.
A couple walked hand in hand, enjoying the cool evening breeze.
Life in the village was peaceful, with a comforting sense of community that made everyone feel at home.
In a quiet village nestled between rolling hills and dense forests, life moved at a gentle pace.
Every morning, the sun would rise slowly over the horizon, casting a warm golden glow across the fields.
The villagers, friendly and hardworking, went about their daily routines with a sense of contentment.
Children played near the stream, their laughter echoing through the trees.
Elderly folks shared stories of olden days on the benches under the large oak tree.
As evening approached, the village would gather around the bonfire, enjoying the simple pleasures of life,
and the stars would shine brightly in the clear night sky.
Binary file added out/artifacts/GNEW_M1_FP_jar/GNEW-M1-FP.jar
Binary file not shown.
8 changes: 7 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
Вдалося реалізувати базові умови до проекту.
В наступному релізі планую реалізувати ще додаткові завдання.
Домашні завдання після лекцій було легко виконувати, а вот поєднати весь пройдений матеріал в одному проекті вже складніше.
Приходилось трішки гуглити бо пройдений матеріал забувається без постійної практики.
В подальшому з набуттям нових знань думаю перепишу проект і зроблю його набагото досконалішим).


## Run the program

Expand Down Expand Up @@ -25,4 +31,4 @@
### Argument could be in any order
```
-e -f "/path/to/file.txt" -k 1
```
```
20 changes: 14 additions & 6 deletions src/main/java/ua/com/javarush/gnew/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,36 @@

import ua.com.javarush.gnew.crypto.Cypher;
import ua.com.javarush.gnew.file.FileManager;
import ua.com.javarush.gnew.file.PathManager;
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 {
//start a project
public static void main(String[] args) {
Cypher cypher = new Cypher();
FileManager fileManager = new FileManager();
ArgumentsParser argumentsParser = new ArgumentsParser();
RunOptions runOptions = argumentsParser.parse(args);
PathManager pathManager = new PathManager();

try {
if (runOptions.getCommand() == Command.ENCRYPT) {
String content = fileManager.read(runOptions.getFilePath());
String encryptedContent = cypher.encrypt(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);
fileManager.write(pathManager.newFilePath(runOptions), encryptedContent);
}
if (runOptions.getCommand() == Command.DECRYPT) {
String content = fileManager.read(runOptions.getFilePath());
String decryptedContent = cypher.decrypt(content, runOptions.getKey());
fileManager.write(pathManager.newFilePath(runOptions), decryptedContent);
}
if (runOptions.getCommand() == Command.BRUTEFORCE) {
String content = fileManager.read(runOptions.getFilePath());
String bruteForceContent = cypher.bruteForce(content);
fileManager.write(pathManager.newFilePath(runOptions), bruteForceContent);
}
Comment on lines 20 to 35
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 contains duplicates. See here how to fix it.

} catch (Exception e) {
System.out.println(e.getMessage());
Expand Down
47 changes: 43 additions & 4 deletions src/main/java/ua/com/javarush/gnew/crypto/Cypher.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package ua.com.javarush.gnew.crypto;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.*;

public class Cypher {
public static int key;
private final ArrayList<Character> 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);
key = -key;

ArrayList<Character> rotatedAlphabet = new ArrayList<>(originalAlphabet);
Collections.rotate(rotatedAlphabet, key);
Expand All @@ -22,6 +21,46 @@ public String encrypt(String input, int key) {
return builder.toString();
}

public String decrypt(String input, int key) {
return encrypt(input, -key);
}

public String bruteForce(String input) {
int maxCount = 0;
int key = 0;
String bestOutput ="";
HashSet<String> engWords = new HashSet<>(List.of("are", "not", "am", "get", "do", "the", "be", "and", "to", "of", "have", "you", "at", "for", "was"));


for (int i = 1; i <= 25; i++) {
ArrayList<Character> rotatedAlphabet = new ArrayList<>(originalAlphabet);
Collections.rotate(rotatedAlphabet, i);
char[] charArray = input.toCharArray();

StringBuilder builder = new StringBuilder();
for (char symbol : charArray) {
builder.append(processSymbol(symbol, rotatedAlphabet));
}
String output = builder.toString();

int count = 0;
String[] words = output.split("\\s+");
for (String word : words) {
if (engWords.contains(word.toLowerCase())) {
count++;
}
}

if (count > maxCount) {
maxCount = count;
key = i;
bestOutput = output;
}
}
Cypher.key = key;
return bestOutput;
Comment on lines +35 to +61
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 a little too complex. It might be simplified and split into methods. See more here

}

private Character processSymbol(char symbol, ArrayList<Character> rotatedAlphabet) {
if (!originalAlphabet.contains(symbol)) {
return symbol;
Expand Down
19 changes: 15 additions & 4 deletions src/main/java/ua/com/javarush/gnew/file/FileManager.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
package ua.com.javarush.gnew.file;

import ua.com.javarush.gnew.runner.RunOptions;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileManager {
public String read(Path filePath) throws IOException {
return Files.readString(filePath);

public String read(Path filePath) {
try {
return Files.readString(filePath);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public void write(Path filePath, String content) throws IOException {
Files.writeString(filePath, content);
public void write(Path filePath, String content) {
try {
Files.writeString(filePath, content);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
26 changes: 26 additions & 0 deletions src/main/java/ua/com/javarush/gnew/file/PathManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package ua.com.javarush.gnew.file;

import ua.com.javarush.gnew.crypto.Cypher;
import ua.com.javarush.gnew.runner.RunOptions;

import java.nio.file.Path;

public class PathManager {
public Path newFilePath(RunOptions runOptions) {
String label = switch (runOptions.getCommand()) {
case ENCRYPT -> " [ENCRYPTED]";
case DECRYPT -> " [DECRYPTED]";
case BRUTEFORCE -> " [BRUTEFORCE]";
default -> null;
};
Comment on lines +10 to +15
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 solution.


String fileName = runOptions.getFilePath().getFileName().toString();
StringBuilder newFileName = new StringBuilder(fileName.substring(0, fileName.length() - 4));
newFileName.append(label);
if (label.equals(" [BRUTEFORCE]")) {
newFileName.append(" key ").append(Cypher.key);
}
newFileName.append(".txt");
return runOptions.getFilePath().resolveSibling(newFileName.toString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public RunOptions parse(String[] args) {
throw new IllegalArgumentException("Command (-e, -d, or -bf) is required");
}

if (key == null) {
if (key == null && command!=Command.BRUTEFORCE) {
throw new IllegalArgumentException("Key is required for encrypt or decrypt mode");
}

Expand Down