AES-256-CBC-Example icon indicating copy to clipboard operation
AES-256-CBC-Example copied to clipboard

Illegal key size

Open arivasvera opened this issue 10 years ago • 5 comments

Exception in thread "main" java.lang.RuntimeException: java.security.InvalidKeyException: Illegal key size
    at AESUtil.encrypt(AESUtil.java:24)
    at AESMain.main(AESMain.java:10)
Caused by: java.security.InvalidKeyException: Illegal key size
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at AESUtil.encrypt(AESUtil.java:21)
    ... 1 more

arivasvera avatar Aug 03 '15 18:08 arivasvera

@andresrivas1506 Hi, I have the same issues as yours, have you fixed that?

yutuoygy avatar May 01 '16 00:05 yutuoygy

Hello @yutuoygy no, I haven't fixed that, sorry

arivasvera avatar May 01 '16 20:05 arivasvera

@arivasvera @yutuoygy Hi there.

You can use that fix:


private AlgorithmParameterSpec makeIv() {
        try {
            return new IvParameterSpec(sha256digest16(ENCRYPTION_IV));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }    
private byte[] sha256digest16(String ivString) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.reset();
        for(int i=0;i<ivString.length();i++)
        {
            digest.update((byte)ivString.charAt(i));
        }
        // so you have 32 bytes here
        byte[]  b = digest.digest();

        // you can return it directly or you can cut it to 16 bytes
        return Arrays.copyOf(b, 16);
    }

Implement that at the AESUtil.class, and obviously replace the makeIv. You can put whatever value you wish to the ENCRYPTION_IV now. We will get the first 16 bytes of the String always.

@yutuoygy , btw thanks for putting that code to open source. It helped me.

kounalem avatar Aug 12 '16 08:08 kounalem

@kounalem:

Your fix doesn't work for me. I replaced the makeIv function, and made both function to public static. But nevertheless, I get:

'Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: java.security.InvalidKeyException: Illegal key size'

julred avatar Nov 05 '17 16:11 julred