-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
190 lines (155 loc) · 7.05 KB
/
Main.java
File metadata and controls
190 lines (155 loc) · 7.05 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.nio.file.*;
import java.security.*;
import java.security.spec.*;
import java.util.*;
public class Main {
// ===== FOLDERS =====
static final Path INPUT_DIR = Paths.get("input");
static final Path ENCRYPTED_DIR = Paths.get("encrypted");
static final Path OUTPUT_DIR = Paths.get("output");
static final Path USER_KEYS = Paths.get("keys/User");
static final Path CLIENT_KEYS = Paths.get("keys/Client");
static final String USER_PRIVATE_KEY = "private.key";
static final String CLIENT_PUBLIC_KEY = "public.key";
static final Set<String> IGNORE = Set.of(".jpg", ".png");
// ===== CRYPTO CONSTANTS =====
static final int AES_KEY_SIZE = 256;
static final int GCM_IV_SIZE = 12;
static final int GCM_TAG_SIZE = 128;
static final int CHUNK_SIZE = 64 * 1024 * 1024; // 64MB
public static void main(String[] args) throws Exception {
Files.createDirectories(ENCRYPTED_DIR);
Files.createDirectories(OUTPUT_DIR);
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
System.out.println("\n1. Encrypt\n2. Decrypt\n3. Exit");
System.out.print("> ");
switch (scanner.nextLine().trim()) {
case "1" -> encryptMode();
case "2" -> decryptMode();
case "3" -> {
System.out.println("Exiting...");
return;
}
default -> System.out.println("Invalid option.");
}
}
}
}
// ================= ENCRYPTION =================
static void encryptMode() throws Exception {
PublicKey clientPub = loadPublicKey(CLIENT_KEYS.resolve(CLIENT_PUBLIC_KEY));
Files.walk(INPUT_DIR)
.filter(Files::isRegularFile)
.forEach(file -> {
try {
if (shouldIgnore(file))
return;
encryptFile(file, clientPub);
Files.delete(file);
System.out.println("✔ Encrypted: " + file);
} catch (Exception e) {
System.out.println("❌ Failed: " + file + " (" + e.getMessage() + ")");
}
});
}
static void encryptFile(Path file, PublicKey rsaPub) throws Exception {
// Generate AES key
KeyGenerator gen = KeyGenerator.getInstance("AES");
gen.init(AES_KEY_SIZE);
SecretKey aesKey = gen.generateKey();
Path relative = INPUT_DIR.relativize(file);
Path encFile = ENCRYPTED_DIR.resolve(relative + ".enc");
Files.createDirectories(encFile.getParent());
try (
InputStream in = new BufferedInputStream(Files.newInputStream(file));
DataOutputStream out = new DataOutputStream(
new BufferedOutputStream(Files.newOutputStream(encFile)))) {
byte[] buffer = new byte[CHUNK_SIZE];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
byte[] iv = new byte[GCM_IV_SIZE];
SecureRandom.getInstanceStrong().nextBytes(iv);
Cipher aes = Cipher.getInstance("AES/GCM/NoPadding");
aes.init(Cipher.ENCRYPT_MODE, aesKey,
new GCMParameterSpec(GCM_TAG_SIZE, iv));
byte[] encrypted = aes.doFinal(buffer, 0, bytesRead);
out.writeInt(encrypted.length); // store chunk length
out.write(iv); // store IV
out.write(encrypted); // store encrypted chunk + tag
}
}
// Encrypt AES key with RSA
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
rsa.init(Cipher.ENCRYPT_MODE, rsaPub);
byte[] encKey = rsa.doFinal(aesKey.getEncoded());
Files.write(encFile.resolveSibling(encFile.getFileName() + ".key"), encKey);
}
// ================= DECRYPTION =================
static void decryptMode() throws Exception {
PrivateKey userPriv = loadPrivateKey(USER_KEYS.resolve(USER_PRIVATE_KEY));
Files.walk(ENCRYPTED_DIR)
.filter(p -> p.toString().endsWith(".enc"))
.forEach(encFile -> {
try {
decryptFile(encFile, userPriv);
System.out.println("✔ Decrypted: " + encFile);
} catch (Exception e) {
System.out.println("❌ Failed: " + encFile + " (" + e.getMessage() + ")");
}
});
}
static void decryptFile(Path encFile, PrivateKey rsaPriv) throws Exception {
Path keyFile = encFile.resolveSibling(encFile.getFileName() + ".key");
if (!Files.exists(keyFile))
throw new SecurityException("Missing key file: " + keyFile);
byte[] encKey = Files.readAllBytes(keyFile);
Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
rsa.init(Cipher.DECRYPT_MODE, rsaPriv);
byte[] aesBytes = rsa.doFinal(encKey);
SecretKey aesKey = new SecretKeySpec(aesBytes, "AES");
Path relative = ENCRYPTED_DIR.relativize(encFile);
Path outFile = OUTPUT_DIR.resolve(relative.toString().replace(".enc", ""));
Files.createDirectories(outFile.getParent());
try (
DataInputStream in = new DataInputStream(
new BufferedInputStream(Files.newInputStream(encFile)));
OutputStream out = Files.newOutputStream(outFile)) {
while (true) {
int len;
try {
len = in.readInt();
} catch (EOFException e) {
break; // finished
}
byte[] iv = in.readNBytes(GCM_IV_SIZE);
byte[] encrypted = in.readNBytes(len);
Cipher aes = Cipher.getInstance("AES/GCM/NoPadding");
aes.init(Cipher.DECRYPT_MODE, aesKey,
new GCMParameterSpec(GCM_TAG_SIZE, iv));
byte[] plain = aes.doFinal(encrypted);
out.write(plain);
}
}
Files.delete(encFile);
Files.delete(keyFile);
}
// ================= UTILITIES =================
static boolean shouldIgnore(Path file) {
String n = file.getFileName().toString().toLowerCase();
return IGNORE.stream().anyMatch(n::endsWith);
}
static PublicKey loadPublicKey(Path path) throws Exception {
byte[] b = Base64.getDecoder().decode(Files.readAllBytes(path));
return KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(b));
}
static PrivateKey loadPrivateKey(Path path) throws Exception {
byte[] b = Base64.getDecoder().decode(Files.readAllBytes(path));
return KeyFactory.getInstance("RSA")
.generatePrivate(new PKCS8EncodedKeySpec(b));
}
}