BadPaddingException when decrypting AES with the same key

牧云@^-^@ 提交于 2019-12-03 03:50:45
weston

You are eating an java.security.InvalidKeyException: Illegal key size or default parameters exception in your encryptAES and decryptAES methods. So don't eat them, either declare as throws or promote to RuntimeException.

Turns out you have two problems, for this reason, you can't do 256, but 128 solves that, then you are also requesting CBC without an IvParameterSpec (Which is causing java.security.InvalidKeyException: Parameters missing). So supply that or change to ECB:

public static byte[] encryptAES(byte[] key, byte[] inputValue)
        throws NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec sKeyS = new SecretKeySpec(key, "AES");

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, sKeyS);

    return cipher.doFinal(inputValue);
}

public static byte[] decryptAES(byte[] key, byte[] encryptedData)
        throws NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec sKeyS = new SecretKeySpec(key, "AES");

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, sKeyS);

    return cipher.doFinal(encryptedData);
}

Key length:

public static byte[] deriveAES256Key(String password)
                throws InvalidKeySpecException, NoSuchAlgorithmException {

   ...
    int keyLength = 128; // 256-bits for AES-256, 128-bits for AES
   ...

So I got it working like that, but step one is to stop eating the exception and you'll get better clues and probably work out on own.

I'm using CBC without an IvParameterSpec.

It was solved adding the following to encrypt and decrypt:

cipher.init(Cipher."mode here", sKeyS, getIvSpecAES256()); 

Where "getIvSpecAES256()" return the same value always.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!