-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
86 lines (71 loc) · 2.81 KB
/
Main.java
File metadata and controls
86 lines (71 loc) · 2.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Cipher.runTests();
Scanner scanner = new Scanner(System.in);
// Question for users:
System.out.print("Do you want to encrypt or decrypt (E/D): ");
String choice = scanner.nextLine().toUpperCase();
System.out.print("Filename: ");
String inputFileName = scanner.nextLine();
System.out.print("Secret key (7 characters): ");
String secretKey = scanner.nextLine();
if (secretKey.length() != 7) {
System.out.println("Error: key must be 7 characters (56 bits).");
return;
}
System.out.print("Output file: ");
String outputFileName = scanner.nextLine();
// read file and convert into Binary:
String fileContent = new String(Files.readAllBytes(Paths.get(inputFileName)));
String binaryInput = toBinary(fileContent);
binaryInput = padBinary(binaryInput);
String resultBinary;
if (choice.equals("E")) {
resultBinary = Cipher.encrypt(binaryInput, secretKey);
} else if (choice.equals("D")) {
resultBinary = Cipher.decrypt(binaryInput, secretKey);
resultBinary = toText(resultBinary);
} else {
System.out.println("Invalid.");
return;
}
// get output file
Files.write(Paths.get(outputFileName), resultBinary.getBytes());
System.out.println("Output saved to " + outputFileName);
}
//// convert plain text to a binary string
public static String toBinary(String text) {
StringBuilder binary = new StringBuilder();
for (char ch : text.toCharArray()) {
binary.append(String.format("%8s", Integer.toBinaryString(ch)).replace(' ', '0'));
}
return binary.toString();
}
// // convert a binary string back to readable text
public static String toText(String binary) {
StringBuilder text = new StringBuilder();
for (int i = 0; i < binary.length(); i += 8) {
text.append((char) Integer.parseInt(binary.substring(i, i + 8), 2));
}
return text.toString();
}
public static String padBinary(String binary) {
int remainder = binary.length() % 64;
if (remainder != 0) {
int padding = 64 - remainder;
binary += "0".repeat(padding);
}
return binary;
}
public static String binaryToTextKey(String binary) {
StringBuilder key = new StringBuilder();
for (int i = 0; i < 56; i += 8) {
int ascii = Integer.parseInt(binary.substring(i, i + 8), 2);
key.append((char) ascii);
}
return key.toString(); // returns 7 char key
}
}