-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCryptoUtil.java
More file actions
38 lines (31 loc) · 1.15 KB
/
Copy pathCryptoUtil.java
File metadata and controls
38 lines (31 loc) · 1.15 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
/*
Project: Simple Password Vault in Java
Structure:
- src/
- CryptoUtil.java
- PasswordVault.java
- Main.java
- vault.txt (created automatically)
*/
// CryptoUtil.java
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class CryptoUtil {
private static final String ALGORITHM = "AES";
public static String encrypt(String data, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encVal = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encVal);
}
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedValue = Base64.getDecoder().decode(encryptedData);
byte[] decValue = cipher.doFinal(decodedValue);
return new String(decValue);
}
}