我正在尝试在Java中加密字符串,并在C#中解密。我首先尝试了RSA / ECB / PKCS1PADDING,效果非常好,但现在我想切换到OAEP填充,但是我无法使其工作。加密运作良好,但解密则不行。我仅更改了Java中的算法名称,在C#中将rsa.Decrypt(data,true)从false更改为true。是否需要进行更多更改?
我得到的异常是“解码OAEP填充时发生错误”。
我的Java加密方法:
我得到的异常是“解码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;
}