/
Encryption.java
59 lines (49 loc) · 1.99 KB
/
Encryption.java
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
package com.denizenscript.depenizen.common.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
public class Encryption {
private SecretKey secret;
private Cipher encryptCipher;
private Cipher decryptCipher;
private byte[] iv;
public Encryption(char[] password, byte[] salt, byte[] iv) throws GeneralSecurityException {
init(password, salt);
this.iv = iv;
finishInit();
}
public Encryption(char[] password, byte[] salt) throws GeneralSecurityException {
init(password, salt);
SecureRandom secureRandom = new SecureRandom();
this.iv = new byte[16];
secureRandom.nextBytes(iv);
finishInit();
}
private void init(char[] password, byte[] salt) throws GeneralSecurityException {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
this.secret = new SecretKeySpec(tmp.getEncoded(), "AES");
}
private void finishInit() throws GeneralSecurityException {
encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
}
public byte[] encrypt(byte[] message) throws GeneralSecurityException {
return encryptCipher.doFinal(message);
}
public byte[] decrypt(byte[] message) throws GeneralSecurityException {
return decryptCipher.doFinal(message);
}
public byte[] getIV() {
return iv;
}
}