I am trying to encrypt at string in Java and decrypt in C#. I tried with RSA/ECB/PKCS1PADDING first and it worked like a charm, but now I'm trying to switch to OAEP padding, but I cannot make it work. The encryption works fine but not the decryption. The only things I changed was the algorithm name in Java and in C# I changed rsa.Decrypt(data, true) from false to true. Does it require more changes?
The exception I get is "Error occurred while decoding OAEP padding".
My Java encryption method:
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;
}
My C# decryption method:
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;
}
It seems to be SHA-256 that's not working with C#. I changed the algorithm name to
"RSA/ECB/OAEPWithSHA-1AndMGF1Padding"
, and it worked!