我得到以下例外之一,而試圖從X509Certificate2證書私鑰:入門異常「無效的提供程序類型指定」或「項不存在」,而從X509Certificate2獲得私鑰偶爾
System.Security.Cryptography.CryptographicException:指定了無效的提供程序類型。
OR
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..ctor(的Int32 dwKeySize,CspParameters參數,布爾useDefaultKeySize)在System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()在Api.CertificateUtil.GetSignedXml(字符串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, "[email protected]");
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;
,有時私鑰被成功從證書文件中取得。截至目前,我們一直無法跟蹤這個問題的模式。