从 Windows 证书存储中查找特定证书 (C# - ASP.Net)

locating a specific certificate from the Windows certificate store (C# - ASP.Net)

我有一个接收签名令牌的 Web 应用程序,应该使用最终用户计算机上预安装的证书来验证该签名。我想访问商店并获得我想要使用的确切的特定证书,到目前为止我能够到达商店并计算里面的证书,但我找不到特定的证书。

我的策略是在 X509Certificate2Collection 中填写证书的搜索结果(按主题名称),因为它足够独特,可以准确选择所需的证书,然后我提取集合中的第一个元素(希望是唯一的) 并使用它,这就是我在下面的代码中所做的,到目前为止,我总是得到一个异常,即 certs 为空,我无法将任何内容转换为字符串。

如果我用序列号搜索,这很好用,但我的证书序列号是 00,我的商店里有 8 个!

如何从商店获取特定证书并能够以编程方式使用它?

X509Store st0re = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
            st0re.Open(OpenFlags.ReadOnly);
            count = st0re.Certificates.Count;       //Count the certificates in the store
            X509Certificate2Collection certs = st0re.Certificates.Find(
                X509FindType.FindBySubjectName,
                "C=US, S=WA, L=Redmond, O=Microsoft Corporation, OU=Web Services",
                true);
            st0re.Close();

            Output = certs[0].ToString();       // = count.ToString()

在考虑了@Crypt32 的建议后,我将我的令牌移动到将托管应用程序的位置,这样我就不会在最终用户的机器上寻找证书,而是将其存储在本地托管应用程序的服务器。为了搜索令牌,我在问题中使用完全相同的代码并进行了非常轻微的编辑:

X509Store st0re = new X509Store(StoreName.Root, StoreLocation.CurrentUser);
        st0re.Open(OpenFlags.ReadOnly);
        count = st0re.Certificates.Count;       //Count the certificates in the store
        X509Certificate2Collection certs = st0re.Certificates.Find(
            X509FindType.FindBySubjectDistinguishedName,
            "C=US, S=WA, L=Redmond, O=Microsoft Corporation, OU=Web Services",
            true);
        st0re.Close();

        Output = certs[0].ToString();       // = count.ToString()

我所做的只是将 X509FindType.FindBySubjectName 替换为 X509FindType.FindBySubjectDistinguishedName 在这种情况下,证书主题中的所有元素都必须以该确切格式列出。