What is the best way to initate a new RSACryptoServiceProvider
object from an X509Certificate2
I pulled out of a key store? The certificate is asso
The recommended way is to use RSA
base class and call certificate.GetRSAPrivateKey()
.
RSA publicKeyProvider = certificate.GetRSAPrivateKey();
Since .NET 4.6, casting to RSACryptoServiceProvider
as suggested by @blowdart is no longer recommended. This is even more an issue now since there are several versions of .NET (such as .NET Core).
By casting to RSACryptoServiceProvider
that way, there is a good chance you might get this cast exception (depending on the platform and libraries used):
Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'
The reason is the actual implementation could be different from each platform, on Windows RSACng
is used.
Here is a link that describes this issue (look for answer by Jeremy Barton).