我们在 java 中有现有的加密代码,并且工作得非常好。我正在尝试在 .net 中创建相同的加密方法,该方法失败的 java 解密方法说错误的填充异常。请参阅下面的代码详细信息: 工作 Java 代码:加密:
private static byte[] doThis(String message) {
byte[] messageCrypte = null;
try {
// Certificate Input Stream
// LA SSL Certificate to be passed.
InputStream inStream = new FileInputStream(certificate);
// X509Certificate created
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
inStream.close();
// Getting Public key using Certficate
PublicKey rsaPublicKey = (PublicKey) cert.getPublicKey();
Cipher encryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
encryptCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] messageACrypter = message.getBytes();
// Encrypted String
messageCrypte = encryptCipher.doFinal(messageACrypter);
} catch (Exception e) {
// TODO: Exception Handling
e.printStackTrace();
}
return messageCrypte;
}
我正在尝试使用等效的 c# .Net 代码,但我从 java 解密代码中得到了错误的填充异常。
static byte[] doThis(string message)
{
X509Certificate cert = new X509Certificate(@"C:\Data\abc-rsa-public-key-certificate.cer");
byte[] aa = cert.GetPublicKey();
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
byte[] Exponent = { 1, 0, 1 };
RSAKeyInfo = RSA.ExportParameters(false);
//Set RSAKeyInfo to the public key values.
RSAKeyInfo.Modulus = aa;
//RSAKeyInfo.Exponent = Exponent;
RSA.ImportParameters(RSAKeyInfo);
byte[] bb = RSA.Encrypt(GetBytes(message), false);
return bb;
}
用于解密的 Java 代码
private String getDecryptedString(byte[] credentials, PrivateKey secretKey) throws NoSuchAlgorithmException,
NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException {
String decryptedString;
Cipher decryptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] messageDecrypte = decryptCipher.doFinal(credentials);
decryptedString = new String(messageDecrypte);
return decryptedString;
}