簡體   English   中英

X509證書未在服務器上加載私鑰文件

[英]X509 certificate not loading private key file on server

我正在使用Google AnalyticsAPI,我按照這個SO問題來設置OAuth: https//stackoverflow.com/a/13013265/1299363

這是我的OAuth代碼:

public void SetupOAuth ()
{
    var Cert = new X509Certificate2(
        PrivateKeyPath, 
        "notasecret", 
        X509KeyStorageFlags.Exportable);
    var Provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, Cert)
    {
        ServiceAccountId = ServiceAccountUser,
        Scope = ApiUrl + "analytics.readonly"
    };
    var Auth = new OAuth2Authenticator<AssertionFlowClient>(Provider, AssertionFlowClient.GetState);
    Service = new AnalyticsService(Auth);
}

PrivateKeyPath是Google API控制台提供的私鑰文件的路徑。 這在我的本地機器上完美運行,但當我把它推到我們的測試服務器時,我得到了

System.Security.Cryptography.CryptographicException: An internal error occurred.

使用以下堆棧跟蹤(刪除不相關的部分):

System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +33
System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +237
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) +140
Metrics.APIs.GoogleAnalytics.SetupOAuth() in <removed>\Metrics\APIs\GoogleAnalytics.cs:36
Metrics.APIs.GoogleAnalytics..ctor(String PrivateKeyPath) in <removed>\Metrics\APIs\GoogleAnalytics.cs:31

因此看起來好像加載文件時遇到了問題。 我檢查了傳入的PrivateKeyPath,它指向正確的位置。

有任何想法嗎? 我不知道這是服務器,文件,代碼還是什么的問題。

我想到的一件事是應用程序池的標識,確保加載用戶配置文件已打開,否則加密子系統不起作用。

我正在加載我的p12文件

new X509Certificate2(
HostingEnvironment.MapPath(@"~/App_Data/GoogleAnalytics-privatekey.p12"), ....

我實際上得到了一個FileNotFoundException,即使File.Exists(filename)返回true。

正如@Wiktor Zychla所說,它就像啟用Load User Profile一樣簡單

這是需要更改的設置的圖像

只需右鍵單擊IIS中“應用程序池”下的應用程序池,然后選擇“高級設置”,您需要的設置大約是一半。

在此輸入圖像描述

提示:我建議您使用此代碼對代碼進行評論,以防止將來浪費時間,因為如果您以前從未遇到過它,那么它就會變得如此模糊。

  // If this gives FileNotFoundException see 
  // http://stackoverflow.com/questions/14263457/

還可以嘗試指定X509KeyStorageFlags

    var certificate = new X509Certificate2(KeyFilePath, KeyFilePassword, 
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | 
X509KeyStorageFlags.Exportable);

如上所述,您需要配置IIS,但在我們的情況下,您需要檢查以下文件夾的權限:

C:\\ ProgramData \\微軟\\加密\\ RSA \\ MachineKeys的

如果設置X509KeyStorageFlags參數,它將在此文件夾中創建一個密鑰文件。 在我的情況下,此文件夾的權限存在差異。 在上述文件夾中未添加池帳戶。

不,是“File.Exists(...)”還處於高級設置? 我有3個池,所有這些池都已啟用“加載用戶配置文件”。 我認為我的問題可能與依賴項和NuGet包有關,因為代碼可以很好地用作控制台應用程序,但在MVC中給我帶來了問題。

暫無
暫無

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

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