簡體   English   中英

在 IIS 服務器上創建 X509Certificate2 對象時出錯

[英]Error during create X509Certificate2 object on IIS server

我在創建 X509Certificate2 對象時遇到問題。

private void OpenKey()
{
    if (!File.Exists(KeyFile))
    {
        return;
    }

    cert = new X509Certificate2(File.ReadAllBytes(KeyFile), KeyPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
    securityKey = new X509SecurityKey(cert);
}

在本地主機上這個工作正常,在開發服務器上也是如此,但在生產服務器上我有錯誤:

Exception: System.Security.Cryptography.CryptographicException: An internal error occurred. at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) at System.Security.Cryptography.X509Certificates.X509Utils.LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle pCertCtx) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password, X509KeyStorageFlags keyStorageFlags) 

我在 .NET Framework 4.5.2 上工作。

我能做些什么來解決這個問題?

@Hazrelle 在評論中是正確的,應用程序池無權將私鑰保存在本地機器存儲中(需要管理員/系統權限)。

而且,實際上,您不應保留動態加載的證書及其密鑰,也無意保留它們。 我有博客文章更詳細地解釋了這一點: https : //www.pkisolutions.com/handling-x509keystorageflags-in-applications/

要解決您的問題,您應該跳過構造函數中的所有存儲標志,即:

cert = new X509Certificate2(File.ReadAllBytes(KeyFile), KeyPassword);

並在課堂上的某個地方保留證書參考,這樣你就可以打電話

cert.Dispose();

完成使用證書后(簽署 JWT 后)從文件系統中刪除私鑰材料。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM