从x509Certificate2启动RSACryptoServiceProvider的最佳方法?

时间:2011-05-03 16:49:28

标签: c# .net cryptography certificate rsacryptoserviceprovider

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

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

由于

3 个答案:

答案 0 :(得分:44)

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

RSACryptoServiceProvider privateKeyProvider = 
    (RSACryptoServiceProvider)certificate.PrivateKey;

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

答案 1 :(得分:8)

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.

答案 2 :(得分:8)

建议的方式是使用RSA基类并致电certificate.GetRSAPrivateKey()

RSA publicKeyProvider = certificate.GetRSAPrivateKey();

从.NET 4.6开始,不再推荐使用@blowdart建议的RSACryptoServiceProvider。由于.NET有多个版本(例如.NET Core),现在这就是一个问题。

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

  

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

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

Here is a link that describes this issue(寻找Jeremy Barton的回答)。