· 9 years ago · Sep 12, 2016, 09:16 AM
1import javax.crypto.Cipher;
2import java.security.spec.KeySpec;
3import javax.crypto.spec.PBEKeySpec;
4import javax.crypto.SecretKey;
5import javax.crypto.spec.SecretKeySpec;
6import javax.crypto.SecretKeyFactory;
7import java.security.AlgorithmParameters;
8import javax.crypto.spec.IvParameterSpec;
9
10public class Decrypter {
11 Cipher dcipher;
12
13 byte[] salt = new String("12345678").getBytes();
14 int iterationCount = 1024;
15 int keyStrength = 256;
16 SecretKey key;
17 byte[] iv;
18
19 Decrypter(String passPhrase) throws Exception {
20 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
21 KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength);
22 SecretKey tmp = factory.generateSecret(spec);
23 key = new SecretKeySpec(tmp.getEncoded(), "AES");
24 dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
25 }
26
27 public String encrypt(String data) throws Exception {
28 dcipher.init(Cipher.ENCRYPT_MODE, key);
29 AlgorithmParameters params = dcipher.getParameters();
30 iv = params.getParameterSpec(IvParameterSpec.class).getIV();
31 byte[] utf8EncryptedData = dcipher.doFinal(data.getBytes());
32 String base64EncryptedData = new sun.misc.BASE64Encoder().encodeBuffer(utf8EncryptedData);
33
34 System.out.println("IV " + new sun.misc.BASE64Encoder().encodeBuffer(iv));
35 System.out.println("Encrypted Data " + base64EncryptedData);
36 return base64EncryptedData;
37 }
38
39 public String decrypt(String base64EncryptedData) throws Exception {
40 dcipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
41 byte[] decryptedData = new sun.misc.BASE64Decoder().decodeBuffer(base64EncryptedData);
42 byte[] utf8 = dcipher.doFinal(decryptedData);
43 return new String(utf8, "UTF8");
44 }
45
46 public static void main(String args[]) throws Exception {
47 Decrypter decrypter = new Decrypter("ABCDEFGHIJKL");
48 String encrypted = decrypter.encrypt("the quick brown fox jumps over the lazy dog");
49 String decrypted = decrypter.decrypt(encrypted);
50 System.out.println(decrypted);
51 }
52}