从x509Certificate2初始化RSACryptoServiceProvider的最佳方法?

X509Certificate2启动新的RSACryptoServiceProvider对象的最佳方法是什么?我从密钥库中取出了什么? 证书与公共(用于加密)和私有(用于解密)密钥相关联。

我目前正在使用FromXmlString方法,但必须有更好的方法。

谢谢

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

 RSACryptoServiceProvider privateKeyProvider = (RSACryptoServiceProvider)certificate.PrivateKey; 

证书的公钥或私钥属性的关键属性是AsymmetricAlgorithm类型。

Blowdart的答案确实是正确的。 但是,为了清楚起见,我应该指出,如果您希望RSACryptoServiceProvider实例包含X509证书的公钥和私钥(假设证书确实有私钥)。 检查证书的HasPrivateKey属性。

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

在RSA的情况下,仅存在公钥时,RSA参数将仅为Exponent和Modulus,所有其他参数将为null; 另一方面,如果存在私钥,则RSA参数将包含D,DP,DQ,指数,反向Q,模数,P和Q.

建议的方法是使用RSA基类并调用certificate.GetRSAPrivateKey()

 RSA publicKeyProvider = certificate.GetRSAPrivateKey(); 

从.NET 4.6开始,不再推荐使用@blowdart建议的转换为RSACryptoServiceProvider 。 由于.NET有多个版本(例如.NET Core),因此这是一个更加严重的问题。

通过这种方式转换为RSACryptoServiceProvider ,很可能会获得此强制转换exception(取决于所使用的平台和库):

无法将类型为“System.Security.Cryptography.RSACng”的对象强制转换为“System.Security.Cryptography.RSACryptoServiceProvider”

原因是实际的实现可能与每个平台不同,在Windows上使用RSACng

这是一个描述这个问题的链接 (寻找Jeremy Barton的回答)。