2017-07-11 34 views
1

我嘗試使用下面的代碼使用自簽名證書:專用密鑰扔類型System.Security.Cryptography.CryptographicException的異常

X509Certificate2 cert = ToCertificate("CN=localhost"); 


public static X509Certificate2 ToCertificate(this string subjectName, 
               StoreName name = StoreName.My, 
               StoreLocation location = StoreLocation.LocalMachine 
               ) 
    { 
     X509Store store = new X509Store(name, location); 

     store.Open(OpenFlags.ReadOnly); 

     try 
     { 
      var cert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(c => c.Subject.Equals(subjectName, StringComparison.OrdinalIgnoreCase)); 

      return cert != null ? new X509Certificate2(cert) : null; 
     } 
     catch (Exception) 
     { 

      throw; 
     } 
     finally 
     { 
      store.Certificates.OfType<X509Certificate2>().ToList().ForEach(c => c.Reset()); 
      store.Close(); 
     } 
    } 

我得到以下異常:

PrivateKey = 'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException' 

enter image description here

我試過this fix,並this fix

但仍然有問題!

+0

來自異常的信息是什麼? – bartonjs

+0

@bartonjs消息:「指定的提供程序類型無效。\ r \ n」 來源:「mscorlib」 –

+0

請運行'certutil -store -silent -v my localhost'並共享結果。 (如果你想要有選擇性,「公鑰算法」和「CERT_KEY_PROV_INFO_PROP_ID(2):」是重要的;但它沒有打印任何內容應該是祕密的) – bartonjs

回答

1

聽起來像您的證書使用CNG密鑰存儲來存儲私鑰。在這種情況下,PrivateKey屬性將在嘗試訪問該屬性時拋出此異常。

爲了正確地訪問密鑰,則必須使用擴展方法來訪問鍵:https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2(v=vs.110).aspx#Extension方法

此外,訪問任何私鑰存儲類型時,無論是遺留(CSP)或優選這些擴展方法CNG。也就是說,不要直接訪問PrivateKeyPublicKey屬性,而是通過這些方法訪問它們。

+0

我將項目升級到.net framework 4.6.1,其中這些擴展方法被定義但仍然有相同的錯誤。 –

0

davidchristiansen說:

什麼是CNG密鑰? Windows中的證書使用存儲提供程序進行存儲。 Windows有兩個這樣的提供者,它們不兼容。舊式「加密服務提供商」或簡稱CSP和新型「加密API:下一代」或CNG。自從Windows Vista開始,CNG提供商就已經出現,雖然它更安全,更易於使用,但許多方面的軟件仍然與CNG提供商不兼容。這似乎也包括.NET Framework。

對此可能的解決方法可能是直接使用CryptoAPI/CNG API來處理CNG密鑰。但是如果我們想要一個更容易理解CNG的純淨.NET解決方案,我們需要找到另一種解決方案(詳情請參閱!)。

我跟隨了以下帖子轉換爲將我的證書密鑰從CNG轉換爲RSA。有用!

http://blog.davidchristiansen.com/2016/05/521/