我试图在Java中加密字符串并在C#中解密。我首先尝试使用RSA / ECB / PKCS1PADDING,它就像一个魅力,但现在我正在尝试切换到OAEP填充,但我无法使其工作。加密工作正常但不解密。我改变的唯一事情是Java中的算法名称,在C#中我将rsa.Decrypt(data,true)从false更改为true。它需要更多变化吗?
我得到的例外是“解码OAEP填充时出错”。
我的Java加密方法:
public byte[] rsaEncrypt(byte[] data) {
byte[] cipherData;
try {
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(pubMod, pubExp);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
cipherData = cipher.doFinal(data);
return cipherData;
} catch (NoSuchAlgorithmException | IllegalBlockSizeException | InvalidKeyException | InvalidKeySpecException | NoSuchPaddingException | BadPaddingException e) {
e.printStackTrace();
}
return null;
}
我的C#解密方法:
private string RSADecrypt(byte[] data)
{
const string PrivateKey = *the key*;
const int PROVIDER_RSA_FULL = 1;
const string CONTAINER_NAME = "Tracker";
CspParameters cspParams;
cspParams = new CspParameters(PROVIDER_RSA_FULL);
cspParams.KeyContainerName = CONTAINER_NAME;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams);
rsa.FromXmlString(PrivateKey);
byte[] decrypted = rsa.Decrypt(data, true);
String decryptedString = System.Text.Encoding.UTF8.GetString(decrypted);
return decryptedString;
}