简体   繁体   中英

Java AES Decryption Exception: javax.crypto.BadPaddingException:

    public static String encrypt(String strToEncrypt) {
        SecureRandom secureRandom = new SecureRandom();
        byte[] key = new byte[16];
        secureRandom.nextBytes(key);
        if (strToEncrypt != null) {
            try {
                IvParameterSpec ivspec = new IvParameterSpec(key);
                SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8), Constants.AES);
                Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
                cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivspec);
                return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
            } catch (Exception ex) {
                LOGGER.error(CommonUtil.exceptionErrorPrefixSuffix("Encryption Exception in DoEncryption::encrypt", ex));
            }
        }
        return null;
    }

    public static String decrypt(String id) throws UnsupportedEncodingException {
        String decryptedId = null;
        SecureRandom secureRandom = new SecureRandom();
        byte[] key = new byte[16];
        secureRandom.nextBytes(key);
        SecretKeySpec keySpec = new SecretKeySpec(Constants.secretKey.getBytes(Constants.UTF_8),Constants.AES);
        byte[] decodedCiphertext = Base64.getDecoder().decode(id);
        try {
            IvParameterSpec ivspec = new IvParameterSpec(key);
            Cipher cipher = Cipher.getInstance(Constants.AES_CBC_PKCS5PADDING);
            cipher.init(Cipher.DECRYPT_MODE, keySpec , ivspec);
            byte[] original = cipher.doFinal(decodedCiphertext);
            decryptedId = new String(original);
            return decryptedId;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

Encryption works fine. but while decryption it throws an exception.

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption. at cipher.doFinal(decodedCiphertext);

Thanks in advance.

Here the problem is you are generating the Key randomly in both the Encryption and decryption method. But since you are using AES algorithm(symmetric algorithm), you should keep the key same for both encryption and decryption.

You need to use the same Secret Key and the same Initialization Vector when decrypting as was used to encrypt. This code uses a different random IV to encrypt than to decrypt. Often the IV is something that can be calculated incrementally by both parties, or it is prepended to the encrypted message if it's random bytes like in this code.

You can reuse the Key over time, but you should not reuse both the Key and the IV for multiple messages. See For AES CBC encryption, whats the importance of the IV? and AES encryption how to transport IV for questions and answers about the Initialization Vector and more information on why not to use a fixed IV or reuse an IV, and so on.

Padding bytes are appended to a message (before encryption) to make its length a multiple of the cipher's block-size (see https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS#5_and_PKCS#7 if interested).

When the byte array is decrypted using a different IV, the decrypted text will not be the same as the plaintext (at least in the first block). If the padding bytes are not the same after being decrypted (which could be the case for a short plaintext), they would not be recognizable and this would cause the BadPaddingException .

( There's another minor issue in this code: It converts the text into bytes to encrypt using the UTF-8 character encoding, but converts the decrypted bytes back into text using the platform default character encoding, which may not be UTF-8. Something like decryptedId = new String(original, "UTF-8"); in the decrypt method would be one possible fix. )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM