无法从Web应用程序中的证书库读取X509证书

时间:2013-02-21 09:01:53

标签: .net security cryptography

从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应用程序中使用上述代码在线看到了示例。

如果代码会从Web应用程序中抛出某种权限异常或某些内容告诉我为什么我无法阅读它们会有所帮助,但事实并非如此。那么,我需要设置某些权限或什么权限吗?

2 个答案:

答案 0 :(得分:1)

我把证书放在TrustedPeople商店中,它工作正常:

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

答案 1 :(得分:0)

要通过权限问题,请将证书导出到.pfx文件(受密码保护)。要使用mmc导出:添加管理单元 - &gt;证书,然后将证书导出(并设置密码)到一个方便的位置。然后

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

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

如果权限允许,可以通过名称访问不在StoreName enums中的商店,例如for&#34; WebHosting&#34;:

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