繁体   English   中英

如何从 X509Store 加载受密码保护的证书?

[英]how to load password protected certificates from the X509Store?

我正在构建一个受 ACS 保护的 Azure WCF 服务,该服务将要求客户端通过证书进行身份验证。

我希望客户端(和服务器)从 X509Store 而不是从文件系统加载各自的密码证书。

我正在使用此代码:

private static X509Certificate2 GetCertificate(string thumbprint)
{
    var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    certStore.Open(OpenFlags.ReadOnly);

    X509Certificate2Collection certCollection = certStore.Certificates.Find(
        X509FindType.FindByThumbprint,
        thumbprint, false);

    certStore.Close();

    if (certCollection.Count == 0)
    {
        throw new System.Security.SecurityException(string.Format(CultureInfo.InvariantCulture, "No certificate was found for thumbprint {0}", thumbprint));
    }

    return certCollection[0]; 
}

问题是,它没有加载身份验证所需的私钥。 我试图将返回语句修改为:

return new X509Certificate2(certCollection[0].Export(X509ContentType.Pfx, "password"));

但是,这会因 CryptographicException“The spcecified network password is不正确”而失败。

编辑:如果不传入密码参数, .Export() 方法可以正常工作。

有什么帮助吗?

导出时,您提供的密码是您要用于导出文件的密码,它不是源证书的密码。

我不确定你可以用X509Store和密码保护的证书做什么,因为密码应该提供给X509Certificate构造函数,你可以从商店中获取已经实例化的对象。

您可以从您想要的证书中获取原始数据,并使用您想要的密码构建一个新数据。 例如:

X509Certificate2 cert = new X509Certificate2(certCollection[0].GetRawCertData, password);

我还建议你在处理密码时尝试使用SecureString (但那是SecureString不同的蠕虫......)

我使用导出没有'密码'参数,它没有问题。

当证书被导入证书存储时,我认为密钥必须被标记为“可导出”,否则我认为你不能导出私钥..

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM