X509证书未在服务器上加载私钥文件

问题描述 投票:41回答:5

我正在使用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,它指向正确的位置。

有任何想法吗?我不知道这是服务器,文件,代码还是什么的问题。

c# asp.net-mvc-3 google-analytics-api x509certificate2
5个回答
83
投票

我想到的一件事是应用程序池的标识,确保加载用户配置文件已打开,否则加密子系统不起作用。


30
投票

我正在加载我的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/

10
投票

还可以尝试指定X509KeyStorageFlags

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

2
投票

如上所述,您需要配置IIS,但在我们的情况下,您需要检查以下文件夹的权限:

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

如果设置X509KeyStorageFlags参数,它将在此文件夹中创建一个密钥文件。在我的情况下,此文件夹的权限存在差异。在上述文件夹中未添加池帐户。


-2
投票

不,是“File.Exists(...)”还处于高级设置?我有3个池,所有这些池都已启用“加载用户配置文件”。我认为我的问题可能与依赖项和NuGet包有关,因为代码可以很好地用作控制台应用程序,但在MVC中给我带来了问题。

© www.soinside.com 2019 - 2024. All rights reserved.