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

时间:2012-09-13 03:48:45

标签: c# .net x509certificate2 pfx

我正在构建一个受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语句修改为:

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

但是,这会因CryptographicException“spcecified网络密码不正确”而失败。

修改 如果你没有传递密码参数,.Export()方法可以正常工作。

对此有何帮助?

2 个答案:

答案 0 :(得分:8)

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

我不确定您可以使用X509Store和受密码保护的证书做什么,因为密码应该提供给X509Certificate构造函数,并且您已经实例化了已经实例化的对象。

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

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

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

答案 1 :(得分:2)

我使用了没有'password'参数的导出,它没有问题。

相关问题