-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncryptionService.java
More file actions
43 lines (36 loc) · 1.68 KB
/
EncryptionService.java
File metadata and controls
43 lines (36 loc) · 1.68 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
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class EncryptionService {
private static final String ALGORITHM = "AES";
public void encrypt(String inputFilePath, String outputFilePath, String password) throws Exception {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
processFile(cipher, inputFilePath, outputFilePath);
}
public void decrypt(String inputFilePath, String outputFilePath, String password) throws Exception {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
processFile(cipher, inputFilePath, outputFilePath);
}
private void processFile(Cipher cipher, String inputFilePath, String outputFilePath) throws Exception {
try (FileInputStream fis = new FileInputStream(inputFilePath);
FileOutputStream fos = new FileOutputStream(outputFilePath)) {
byte[] inputBytes = new byte[64];
int bytesRead;
while ((bytesRead = fis.read(inputBytes)) != -1) {
byte[] outputBytes = cipher.update(inputBytes, 0, bytesRead);
if (outputBytes != null) {
fos.write(outputBytes);
}
}
byte[] outputBytes = cipher.doFinal();
if (outputBytes != null) {
fos.write(outputBytes);
}
}
}
}