【发布时间】:2022-03-07 08:01:00
【问题描述】:
我正在使用以下代码进行加密和解密,而解密时我在运行时遇到错误。错误消息是“非法 base64 字符 20”
加密代码:
String secretValue = "sazhwsxplokmeroo";
keyValue = secretValue.getBytes();
Key generatedKey = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, generatedKey);
byte[] encValue = c.doFinal(userEmail.getBytes());
String encryptedValue = Base64.getEncoder().encodeToString(encValue);
密钥:
private Key generateKey() {
Key secretKey = new SecretKeySpec(keyValue, ALGO);
return secretKey;
}
解密代码:
String secretValue = "sazhwsxplokmeroo";
keyValue = secretValue.getBytes();
Key generatedKey = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, generatedKey);
byte[] decodedValue = Base64.getDecoder().decode(encryptEmail.getBytes()); //error throws from this line as illegal base64 character 20
byte[] decValue = c.doFinal(decodedValue);
String decryptedValue = decValue.toString();
我怎样才能不出错地解密加密值
加密值 = 3aW0qv4pN+y3Tj8raXDHtos95ChpLu2JzEnfW+KfgEE=
这个值在 spring 控制器中显示为 = 3aW0qv4pN y3Tj8raXDHtos95ChpLu2JzEnfW KfgEE=
它显示两个空格“+”被转换为“(空格)”
现在我已将我的密钥更改为“sa278asabmnbmnbm”
我得到的加密值为 40SRNEe9PgaxEeprPyqlyeP08hBHq00Ow9WWBgP6ZTM=
解密时我得到 [B@75141845 作为解密值
预期:shamith@alraislabs.in
【问题讨论】:
-
encryptEmail的值是多少?里面有空格吗? -
是的,加密代码中出现的“+”被spring控制器转换为空间
-
因为忘记对 Base64 字符串进行 URL 编码,所以
+本来应该是%2B。 -
解决问题的任何建议/
-
是的,对 Base64 字符串进行 URL 编码 (我已经告诉过你,你忘了这样做),然后再将其发送到 Web 服务器,也就是弹簧控制器。