【问题标题】:Cannot read X509 certificates from certificate store in a web application无法从 Web 应用程序的证书存储中读取 X509 证书
【发布时间】:2013-02-21 09:01:52
【问题描述】:

从 Web 应用程序运行此代码时,我看不到任何 X509 证书:

var store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            string thumbprint = WebConfigurationManager.AppSettings["CertificateThumbprint"];

            if (string.IsNullOrWhiteSpace(thumbprint))
            {
                throw new ArgumentException("Please specify the X509 certificate thumbprint in the web configuration file.");
            }

            Certificate = store.Certificates
                .Find(X509FindType.FindByThumbprint, thumbprint, true)
                .OfType<X509Certificate2>()
                .FirstOrDefault();

            store.Close();

            if (Certificate == null)
            {
                throw new ArgumentException("The specified X509 certificate has not been installed on this server.");
            }

调试的时候可以看到store.Certificates是空的。但是,它在控制台应用程序中运行得非常好。这很奇怪,因为我在网上看到了在 Web 应用程序中使用上述代码的示例。

如果代码会抛出某种权限异常或来自网络应用程序的某些东西来告诉我为什么我无法阅读它们,那将会很有帮助,但事实并非如此。那么,我需要在某处设置一些权限吗?

【问题讨论】:

    标签: .net security cryptography


    【解决方案1】:

    我将证书放在 TrustedPeople 存储中,它工作正常:

    var store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);

    【讨论】:

      【解决方案2】:

      要解决权限问题,请将证书导出到 .pfx 文件(受密码保护)。要使用 mmc 导出:添加管理单元 -> 证书,然后将证书导出(并设置密码)到方便的位置。那么

      var certF = new X509Certificate2(
                          @"D:\somedir\withaccess\exported.pfx", "password!");
      

      为什么要从StoreName.Root 移出用于受信任的根证书颁发机构的证书?

      如果权限允许,可以通过名称访问不在StoreName enums 中的存储,例如对于“网络托管”:

      var store = new X509Store( "WebHosting", StoreLocation.LocalMachine);
      

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 1970-01-01
        • 2011-01-01
        • 2019-12-06
        • 2014-03-30
        • 1970-01-01
        • 1970-01-01
        • 2015-03-04
        • 2012-02-20
        相关资源
        最近更新 更多