尝试从X509Certificate2证书获取私钥时,我收到以下异常之一:
System.Security.Cryptography.CryptographicException:指定了无效的提供程序类型.
要么
System.Security.Cryptography.CryptographicException:以下代码行中不存在键:RSACryptoServiceProvider rsaKey =(RSACryptoServiceProvider)digiSignCert.PrivateKey;
堆栈跟踪:
System.Security.Cryptography.CryptographicException:键不存在.在System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType关键字类型,CspParameters参数,布尔randomKeyContainer,的Int32 dwKeySize,SafeProvHandle&safeProvHandle,SafeKeyHandle&safeKeyHandle)在System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()在System.Security.Cryptography.RSACryptoServiceProvider.位于Api.CertificateUtil.GetSignedXml(String xml,X509Certificate2 privateCert)的System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()中的.ctor(Int32 dwKeySize,CspParameters参数,布尔值useDefaultKeySize)
码:
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
}
Run Code Online (Sandbox Code Playgroud)
预期结果:(RSACryptoServiceProvider)privateCert.PrivateKey
应始终生成私钥.
实际结果:有时上述异常会抛出此行:
rsaKey = (RSACryptoServiceProvider)privateCert.PrivateKey;
有时,从证书文件中成功获取私钥.截至目前,我们无法跟踪此问题的模式.
c# cryptography rsacryptoserviceprovider x509certificate2 x509certificate