· 8 years ago · Nov 30, 2017, 01:04 PM
1import java.security.Key;
2import java.security.spec.KeySpec;
3import java.util.Base64;
4
5import javax.crypto.Cipher;
6import javax.crypto.SecretKey;
7import javax.crypto.SecretKeyFactory;
8import javax.crypto.spec.PBEKeySpec;
9import javax.crypto.spec.SecretKeySpec;
10
11public class Crypto {
12
13 private static final String _algorithm = "AES";
14 private static final String _password = "_pasword_to_generate_secret-key-encryption*";
15 private static final String _salt = "_salt_to_generate_secret-key-encryption*";
16 private static final String _keygen_spec = "PBKDF2WithHmacSHA1";
17 private static final String _cipher_spec = "AES/CBC/PKCS5Padding";
18
19 public static String encrypt(String data) throws Exception {
20 Key key = getKey();
21 System.out.println(key.toString());
22 Cipher cipher = Cipher.getInstance(_cipher_spec);
23 cipher.init(Cipher.ENCRYPT_MODE, key);
24 byte[] encVal = cipher.doFinal(data.getBytes());
25 String encryptedValue = Base64.getEncoder().encodeToString(encVal);
26 System.out.println("Encrypted value of "+data+": "+encryptedValue);
27 return encryptedValue;
28 }
29
30 public static void decrypt(String encryptedData) throws Exception {
31 Key key = getKey();
32 System.out.println(key.toString());
33 Cipher cipher = Cipher.getInstance(_cipher_spec);
34 cipher.init(Cipher.DECRYPT_MODE, key);
35 byte[] decordedValue = Base64.getDecoder().decode(encryptedData);
36 byte[] decValue = cipher.doFinal(decordedValue);
37 String decryptedValue = new String(decValue);
38 System.out.println("Decrypted value of "+encryptedData+": "+decryptedValue);
39 }
40
41 private static Key getKey() throws Exception {
42 SecretKeyFactory factory = SecretKeyFactory.getInstance(_keygen_spec);
43 KeySpec spec = new PBEKeySpec(_password.toCharArray(), _salt.getBytes(), 65536, 128);
44 SecretKey tmp = factory.generateSecret(spec);
45 SecretKey secret = new SecretKeySpec(tmp.getEncoded(), _algorithm);
46 return secret;
47 }
48
49 public static void main(String []str) throws Exception {
50 String value = encrypt("India@123");
51 decrypt(value);
52 }
53}
54
55javax.crypto.spec.SecretKeySpec@17111
56Encrypted value of India@123: iAv1fvjMnJqilg90rGztXA==
57javax.crypto.spec.SecretKeySpec@17111
58Exception in thread "main" java.security.InvalidKeyException: Parameters missing
59 at com.sun.crypto.provider.CipherCore.init(CipherCore.java:469)
60 at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313)
61 at javax.crypto.Cipher.implInit(Cipher.java:802)
62 at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
63 at javax.crypto.Cipher.init(Cipher.java:1249)
64 at javax.crypto.Cipher.init(Cipher.java:1186)
65 at org.lp.test.Crypto.decrypt(Crypto.java:37)
66 at org.lp.test.Crypto.main(Crypto.java:54)