我有这种加密方法:
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(message);
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:解密错误
正如我所看到的,我已将密码配置为具有相同的PKCS1Padding
,所以我无法猜测为什么会收到该错误。
我已经如下创建了我的私钥:
openssl genrsa -out myPrivateKey.key 2048
和公众一个:
openssl rsa -in myPrivateKey.pem -pubout -out myPublicKey.key
据我所见,它们都是PKCS1,实际上我的私钥以-----BEGIN RSA PRIVATE KEY-----
开头。
我想念什么?
注意:我也尝试过blockSize = 64
,结果相同。
加密流-正确地,您应该在循环中具有cipher.update(..)
,并且在处理所有数据之后仅应调用一次.doFinal(..)
。
解密时,如果在部分消息上调用doFinal
,则可能会出现异常。无论这是您面临的问题,从代码中看不出来。 (假设您正确导入了密钥对)
并且实际上RSA仅用于短(117字节)消息。否则,您可以搜索“混合加密”