gpt4 book ai didi

使用 Base64 的解密方法中的 javax.crypto.BadPaddingException

转载 作者:行者123 更新时间:2023-12-03 04:32:27 25 4
gpt4 key购买 nike

我正在使用下面的代码加密和解密密码。

public static String encrypt(String data, Key key) throws Exception {

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
byte[] base64Bytes = Base64.encodeBase64(encryptedBytes);
String base64EncodedString = new String(base64Bytes);
return base64EncodedString;
}

public static String decrypt(String encrypted, Key key) throws Exception {

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decoded = Base64.decodeBase64(encrypted.getBytes());
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted);
}

加密工作正常。异常(exception)是在 decrypt 方法的 doFinal 方法处抛出异常。

异常:

[4/4/14 12:36:59:522 CDT] 00000024 SystemErr R Caused by: javax.crypto.BadPaddingException: Not PKCS#1 block type 2 or Zero padding [4/4/14 12:36:59:523 CDT] 00000024 SystemErr R at com.ibm.crypto.provider.RSA.engineDoFinal(Unknown Source) [4/4/14 12:36:59:523 CDT] 00000024 SystemErr R at javax.crypto.Cipher.doFinal(Unknown Source) [4/4/14 12:36:59:523 CDT] 00000024 SystemErr R at com.moneygram.webpoe.util.SecurityProvider.decrypt(SecurityProvider.java:171) [4/4/14 12:36:59:524 CDT] 00000024 SystemErr R at com.moneygram.webpoe.util.SecurityProvider.decrypt(SecurityProvider.java:137)

如果有人对此有任何解决方案,请帮助我?如果这是不完整的信息,我可以提供。我被这个困住了!!!

最佳答案

我不确定您的问题,但我确实知道您过于依赖默认值 - 对于 key 、字符集和加密模式+填充模式。

尝试以下操作,请指出这是否可以解决您的问题:

public static String encrypt(String data, RSAPublicKey key) throws Exception {

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(encryptedBytes);
}

public static String decrypt(String encrypted, RSAPrivateKey key) throws Exception {

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decoded = Base64.decodeBase64(encrypted);
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted, StandardCharsets.UTF_8);
}

关于使用 Base64 的解密方法中的 javax.crypto.BadPaddingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22919265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com