注意: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/