我在我的解密方法中得到了BadPaddingException



我正在使用以下(片段(代码来加密用户的私人数据以存储在数据库中,然后解密以便他们可以查看它。

Cipher cipher = Cipher.getInstance("DESede");
byte[] bytes = cipher.doFinal(value.getBytes());
String encrypted = new String(bytes);

然后将此字符串存储在数据库中的 varchar 列下

要解密:

Cipher cipher = Cipher.getInstance("DESede");
byte[] bytes = cipher.doFinal(value.getBytes());
String decrypted = new String(bytes);[code]

现在看似随机,我偶尔会得到

javax.crypto.BadPaddingException: Given final block not properly padded

从加密中获取的数据是二进制的。您无法安全地将byte[]转换为 String 并像现在这样转换回来,因为并非所有字节都有来回 1-1 映射。将数据保存在可以处理二进制数据的字段中,或者使用不会丢失数据的编码(如 base64十六进制编码(对数据进行编码。

String encrypted = new String(bytes);

问题就在这里。 String不是二进制数据的容器。使用byte[],或者十六进制或 base64 编码,如果必须有一个String

相关内容

  • 没有找到相关文章

最新更新