【发布时间】:2018-01-08 14:31:42
【问题描述】:
我在尝试从 X509Certificate2 证书获取私钥时遇到以下异常之一:
System.Security.Cryptography.CryptographicException:指定的提供程序类型无效。
或
System.Security.Cryptography.CryptographicException:以下代码行中不存在密钥:RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)digiSignCert.PrivateKey;
堆栈跟踪:
System.Security.Cryptography.CryptographicException:密钥不存在。在 System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters 参数, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) 在 System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() 在 System.Security.Cryptography.RSACryptoServiceProvider。 .ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey() at Api.CertificateUtil.GetSignedXml(String xml, X509Certificate2 privateCert)
代码:
public static RSACryptoServiceProvider rsaKey = null;
public X509Certificate2 _PrivateCert;
public APISearch()
{
byte[] privateCert = null;//We get the actual certificate file data here
GetPrivateCerificate(privateCert, "abc@123");
GetSignedXml(_PrivateCert);
}
public void GetPrivateCerificate(byte[] privateCert, string pwd)
{
_PrivateCert = new X509Certificate2(privateCert, pwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
}
public void GetSignedXml(X509Certificate2 privateCert)
{
rsaKey = (RSACryptoServiceProvider)privateCert.PrivateKey; //Occassional Exception
}
预期结果:(RSACryptoServiceProvider)privateCert.PrivateKey 应始终生成私钥。
实际结果:有时会在这一行抛出上述异常:
rsaKey = (RSACryptoServiceProvider)privateCert.PrivateKey;
有时会从证书文件中成功获取私钥。截至目前,我们无法追踪此问题的模式。
【问题讨论】:
标签: c# cryptography x509certificate x509certificate2 rsacryptoserviceprovider