gpt4 book ai didi

java - 尝试解密时出现 BadPaddingException - Java

转载 作者:行者123 更新时间:2023-12-02 09:11:06 25 4
gpt4 key购买 nike

我有这种加密方法:

private byte[] encrypt(byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, myPublicKey);
ByteArrayInputStream input = new ByteArrayInputStream(data);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[64];
int bytes;
ByteArrayOutputStream aux;
try {
while ((bytes = input.read(buffer)) != -1) {
aux = new ByteArrayOutputStream();
aux.write(buffer, 0, bytes);
byte[] fragment = aux.toByteArray();
byte[] encryptedFragment = cipher.doFinal(fragment);
output.write(encryptedFragment);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] result = output.toByteArray();
return result;
}

这个用于解密:

public static String decrypt(byte[] data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IOException {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, myPrivateKey);
int bitLenght = ((java.security.interfaces.RSAPrivateKey) privateKey).getModulus().bitLength();
int blockSize = bitLenght / 8;
byte[] buffer = new byte[blockSize];
int bytes;
byte[] decrypted;
ByteArrayOutputStream aux;
ByteArrayInputStream input = new ByteArrayInputStream(data);
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytes = input.read(buffer)) != -1) {
aux = new ByteArrayOutputStream();
aux.write(buffer, 0, bytes);
byte[] fragment = aux.toByteArray();

byte[] decryptedFragment = cipher.doFinal(fragment);
output.write(decryptedFragment);
}
decrypted = output.toByteArray();

return new String(decrypted);
}

但是我遇到了这个异常:

javax.crypto.BadPaddingException: Decryption error

正如我所见,我已将密码配置为具有相同的 PKCS1Padding,因此我无法猜测为什么会出现该错误。

我已按如下方式创建了私钥:

openssl genrsa -out myPrivateKey.key 2048

还有公共(public)的:

openssl rsa -in myPrivateKey.pem -pubout -out myPublicKey.key

据我所知,通过该命令它们都是 PKCS1,事实上我的私钥以 -----BEGIN RSA PRIVATE KEY----- 开头。

我错过了什么?

注意:我也尝试过使用 blockSize = 64,结果相同。

最佳答案

加密流 - 正确地,您应该在循环中使用 cipher.update(..) ,并在处理所有数据后仅调用一次 .doFinal(..)

解密时,如果您对部分消息调用doFinal,您可能会遇到异常。不管怎样,从您的代码中看不出来这是否是您面临的问题。 (假设您已正确导入 key 对)

事实上,RSA 仅适用于短消息(117 字节)。否则您可以搜索“混合加密”

P。 S.:你处理流和数组的方式迫切需要优化,所以也看看它,但那是针对不同的问题

关于java - 尝试解密时出现 BadPaddingException - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59411645/

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