我有这种加密方法:
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,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,BadPaddingException,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,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
,结果也一样。