· 8 years ago · Dec 14, 2017, 08:06 AM
1import javax.crypto.Cipher;
2import javax.crypto.SecretKey;
3import javax.crypto.SecretKeyFactory;
4import javax.crypto.spec.IvParameterSpec;
5import javax.crypto.spec.PBEKeySpec;
6import javax.crypto.spec.SecretKeySpec;
7import java.security.AlgorithmParameters;
8import java.security.spec.KeySpec;
9
10public class JCE {
11
12 private static final char[] PASSWORD = "abcdefg".toCharArray();
13
14 private static final byte[] SALT =
15 {
16 (byte)0x4D, (byte)0x9B, (byte)0xC6, (byte)0x53,
17 (byte)0x17, (byte)0xAF, (byte)0xE2, (byte)0x08
18 };
19
20 private static final int iterations = 65536;
21
22 public static void main(String... args) throws Exception {
23 String data = "Test";
24 for (String arg : args) {
25 data += ":" + arg;
26 }
27
28 System.out.println("Encrypting, \"" + data + "\"");
29
30 JCE jce = new JCE();
31 byte[] encryptedData = jce.encrypt(data);
32 System.out.println("Encrypted: " + new String(encryptedData));
33
34 byte[] decipheredText = jce.decrypt(encryptedData);
35 System.out.println("Decrypted: " + new String(decipheredText));
36 }
37
38 private byte[] initializationVector;
39
40 private byte[] encrypt(String property) throws Exception {
41 Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
42 return cipher.doFinal(property.getBytes());
43 }
44
45 private byte[] decrypt(byte[] property) throws Exception {
46 Cipher pbeCipher = getCipher(Cipher.DECRYPT_MODE);
47 return pbeCipher.doFinal(property);
48 }
49
50 private Cipher getCipher(int mode) throws Exception {
51 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
52 KeySpec spec = new PBEKeySpec(PASSWORD, SALT, iterations, 256);
53 SecretKey tmp = factory.generateSecret(spec);
54 SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES");
55
56 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
57 if (this.initializationVector == null) {
58 cipher.init(mode, key);
59 AlgorithmParameters params = cipher.getParameters();
60 this.initializationVector = params.getParameterSpec(IvParameterSpec.class).getIV();
61 } else {
62 cipher.init(mode, key, new IvParameterSpec(this.initializationVector));
63 }
64
65 return cipher;
66 }
67}