C# equivalent to Java RSA/ECB/OAEPWithSHA-256AndMGF1Padding

后端 未结 2 1473
陌清茗
陌清茗 2021-01-13 18:54

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

相关标签:
2条回答
  • 2021-01-13 19:17

    RSACryptoServiceProvider does not support OAEP-SHA2.

    .NET 4.6 added RSACng, which is capable of OAEP-SHA2 (256, 384, 512). .NET 4.6 also changed the Encrypt/Decrypt and Sign/Verify signatures a bit to be more scalable than a Boolean, and moved them to the RSA base class:

    using (RSA rsa = new RSACng())
    {
        rsa.FromXmlString(privateKeyXml);
        byte[] decrypted = rsa.Decrypt(data, RSAEncryptionPadding.OaepSHA256);
        return Encoding.UTF8.GetString(decrypted);
    }
    

    If your private key comes from an X509Certificate2 instance the new GetRSAPrivateKey method (also in 4.6) will prefer a RSACng instance; though the return type is deliberately not guaranteed... so if you must cast it you should use as instead of a hard cast.

    0 讨论(0)
  • 2021-01-13 19:43

    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!

    0 讨论(0)
提交回复
热议问题