首页 > 解决方案 > Java AES 解密异常: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;
    }

加密工作正常。但是在解密时会引发异常。

javax.crypto.BadPaddingException:给定最终块未正确填充。如果在解密期间使用了错误的密钥,则可能会出现此类问题。在 cipher.doFinal(decodedCiphertext);

提前致谢。

标签: javaaes

解决方案


这里的问题是您在加密和解密方法中随机生成密钥。但由于您使用的是 AES 算法(对称算法),因此加密和解密的密钥应保持相同。


推荐阅读