· 7 years ago · Jun 20, 2018, 05:36 AM
1java.security.InvalidKeyException: Illegal key size or default parameters
2
3public class Encryption {
4
5 public static class MessageEncrypt {
6
7 public static class AES {
8 private final static String ALGO = "AES";
9 private String secretKey;
10 private String data;
11
12 public String encrypt(String secretKey, String data) throws Exception {
13 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
14 KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 128, 256);
15 SecretKey tmp = factory.generateSecret(spec);
16 SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGO);
17 Cipher cipher = Cipher.getInstance(ALGO);
18 cipher.init(Cipher.ENCRYPT_MODE, key);
19 return toHex(cipher.doFinal(data.getBytes()));
20 }
21
22 public String decrypt(String secretKey, String data) throws Exception {
23 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
24 KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), secretKey.getBytes(), 128, 256);
25 SecretKey tmp = factory.generateSecret(spec);
26 SecretKey key = new SecretKeySpec(tmp.getEncoded(), ALGO);
27 Cipher cipher = Cipher.getInstance(ALGO);
28 cipher.init(Cipher.DECRYPT_MODE, key);
29 return new String(cipher.doFinal(toByte(data)));
30 }
31
32 private static byte[] toByte(String hexString) {
33 int len = hexString.length() / 2;
34 byte[] result = new byte[len];
35 for (int i = 0; i < len; i++)
36 result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
37 return result;
38 }
39
40 public static String toHex(byte[] stringBytes) {
41 StringBuffer result = new StringBuffer(2 * stringBytes.length);
42 for (int i = 0; i < stringBytes.length; i++) {
43 result.append(HEX.charAt((stringBytes[i] >> 4) & 0x0f)).append(HEX.charAt(stringBytes[i] & 0x0f));
44 }
45 return result.toString();
46 }
47
48 private final static String HEX = "0123456789ABCDEF";
49 }
50 }
51
52 static class DataEncrypt {
53
54 }
55
56}
57
58public class Testing {
59
60 public static void main(String[] args) throws Exception {
61
62 AES cryptoAES = new AES();
63 System.out.println(cryptoAES.encrypt("43234sfeff", "re"));
64
65 }
66
67}
68
69Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
70 at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1021)
71 at javax.crypto.Cipher.implInit(Cipher.java:796)
72 at javax.crypto.Cipher.chooseProvider(Cipher.java:859)
73 at javax.crypto.Cipher.init(Cipher.java:1229)
74 at javax.crypto.Cipher.init(Cipher.java:1166)
75 at com.detroit.Encryption$MessageEncrypt$AES.encrypt(Encryption.java:35)
76 at testing.Testing.main(Testing.java:10)