Best way to initiate RSACryptoServiceProvider from x509Certificate2?

浪尽此生 提交于 2019-11-27 13:34:45

问题


What is the best way to initate a new RSACryptoServiceProvider object from an X509Certificate2 I pulled out of a key store? The certificate is associated with both public (for encryption) and private (for decryption) keys.

I'm current using the FromXmlString method but there must be a better way.

Thanks


回答1:


RSACryptoServiceProvider publicKeyProvider = 
    (RSACryptoServiceProvider)certificate.PublicKey.Key;

and

RSACryptoServiceProvider privateKeyProvider = 
    (RSACryptoServiceProvider)certificate.PrivateKey;

The key property on the public or private key property of the certificate is of type AsymmetricAlgorithm.




回答2:


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).




回答3:


Blowdart's answer is indeed correct. However, for clarity I should point out that if you want your RSACryptoServiceProvider instance to contain both the public and private keys of the X509 certificate (assuming the certificate does have a private key). Check the certificate's HasPrivateKey property.

RSACryptoServiceProvider rsa;
if (cert.HasPrivateKey)
    rsa = (RSACryptoServiceProvider)cert.PrivateKey;
else
    rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;

In the case of RSA when only the public key is present the RSA Parameters will be only Exponent and Modulus, all others will be null; If on the other hand the private key is present the RSA Parameters will contain D, DP, DQ, Exponent, InverseQ, Modulus, P and Q.



来源:https://stackoverflow.com/questions/5872868/best-way-to-initiate-rsacryptoserviceprovider-from-x509certificate2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!