· 9 years ago · Oct 04, 2016, 01:32 PM
1KeyGenerator keyGen;
2
3try {
4 keyGen = KeyGenerator.getInstance("AES");
5 keyGen.init(256);
6 SecretKey secretKey = keyGen.generateKey();
7 return secretKey;
8}
9catch (Exception e) {
10 e.printStackTrace();
11 return null;
12}
13
14private byte[] aes256Encode(SecretKey key, IvParameterSpec iv, String message) throws InvalidKeyException,
15 InvalidAlgorithmParameterException,
16 NoSuchAlgorithmException, NoSuchPaddingException,
17 IllegalBlockSizeException, BadPaddingException
18 {
19 Cipher cipher = Cipher.getInstance("AES/CFB/PKCS5Padding");
20 cipher.init(Cipher.ENCRYPT_MODE, key, iv);
21 byte[] encrypted = cipher.doFinal(message.getBytes());
22 return encrypted;
23 }
24
25private IvParameterSpec generateAESIV() {
26 // build the initialization vector (randomly).
27 SecureRandom random = new SecureRandom();
28 byte iv[] = new byte[16];//generate random 16 byte long
29 random.nextBytes(iv);
30 IvParameterSpec ivspec = new IvParameterSpec(iv);
31 return ivspec;
32 }
33
34Exception in thread "main" java.security.InvalidKeyException: Illegal key size
35 at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1039)
36 at javax.crypto.Cipher.implInit(Cipher.java:805)
37 at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
38 at javax.crypto.Cipher.init(Cipher.java:1396)
39 at javax.crypto.Cipher.init(Cipher.java:1327)