Java AES解密BadPaddingException

标签 java encryption cryptography aes badpaddingexception

注意:Java NOOB。

好吧,我知道这个问题已经在这里回答了几十次,但这些解决方案似乎不起作用/直接适用于我理解的地方。 (是的,我知道我不完全理解加密/解密、AES 等,但这不是重点,我正在尝试理解这一点)

我有一个实用程序 api,我想在其中传递一个字符串并返回一个加密的字符串。然后我想传递加密的字符串,并返回解密的字符串。简单的。对于我传入的许多字符串来说,它工作得很好,但在某些字符串上,我收到异常 javax.crypto.BadPaddingException: 鉴于最终 block 未正确填充。

例如,以下加密/解密效果很好。
util/encrypt/?token=123456789012wha = 4TR0CbCcQKqeRK73zr83aw==
util/decrypt/?token=4TR0CbCcQKqeRK73zr83aw== = 123456789012wha

以下内容加密,但不解密:
util/encrypt/?token=123456789012what = NYaWmwnySoGNHyNmY9Jh+f3O2rqoLI1IAcnsl5V4OCE=
util/decrypt/?token=NYaWmwnySoGNHyNmY9Jh+f3O2rqoLI1IAcnsl5V4OCE= = 异常

这是我的 Controller 中的代码:

private static final String ALGO = "AES";


@RequestMapping(value = "/util/encrypt/", method = RequestMethod.GET)
@ResponseBody
public String encrypt(HttpServletResponse httpResponse,
        @RequestParam(value = "token", required=true) String token) throws Exception 
{
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(token.getBytes());
    String encryptedValue = Base64.encodeBase64String(encVal);
    return encryptedValue.trim();
}



@RequestMapping(value = "/util/decrypt/", method = RequestMethod.GET)
@ResponseBody
public String decrypt(HttpServletResponse httpResponse,
        @RequestParam(value = "token", required=true) String token) throws Exception 
{
    token = URLDecoder.decode(token, "UTF-8");
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decordedValue = Base64.decodeBase64(token);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue.trim();
}



private Key generateKey() throws Exception 
{
    Key key = new SecretKeySpec(getAesKey().getBytes(), ALGO);
    return key;
}

我认为它一定是与调用 Cipher.getInstance() 相关的内容,并且我尝试使用 Cipher.getInstance("AES/CBC/PKCS5Padding") 但是解密时总是失败。我很想真正了解这里发生了什么以及如何解决它。

最佳答案

使用函数encodeBase64URLSafeString 。 javadoc 说

Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the output. The url-safe variation emits - and _ instead of + and / characters. Note: no padding is added.

这应该可以解决问题。

关于Java AES解密BadPaddingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17286045/

相关文章:

java - HashMap 键更新与双条目

algorithm - 为什么需要大量随机性才能进行有效加密?

python - 如何将 AES 模式从一种迁移到另一种?

java - 如何在 Java 中解密 sha1 加密的字符串

python - PowerShell 和 Python 中的 AES 加密

python - 如何使用 Python gnupg 模块验证 gnupg 签名?

java - Axis2 生成的服务创建错误的请求

java - 如何将Spring Boot应用程序指向外部jar的logback.xml

java - XMLWorkerHelper 性能缓慢

java - 如何通过DataSourceBuilder将jasypt加密密码传递给数据库