简体   繁体   English

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

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

I am building an ACS protected Azure WCF service that will require clients to authenticate via a certificate.我正在构建一个受 ACS 保护的 Azure WCF 服务,该服务将要求客户端通过证书进行身份验证。

I would like the client (and the server) to load their respective password certs from the X509Store instead of from the file system.我希望客户端(和服务器)从 X509Store 而不是从文件系统加载各自的密码证书。

I am using this code:我正在使用此代码:

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]; 
}

Problem is, it's not loading the private key which it needs for authentication.问题是,它没有加载身份验证所需的私钥。 I have tried to modify the return statement to this:我试图将返回语句修改为:

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

However, this fails with a CryptographicException "The spcecified network password is incorrect".但是,这会因 CryptographicException“The spcecified network password is不正确”而失败。

Edit: The .Export() method works properly if you don't pass the password argument in.编辑:如果不传入密码参数, .Export() 方法可以正常工作。

Any help on this?有什么帮助吗?

When you export, the password you provide is the password you want to use for the exported file, it's not the password for the source certificate. 导出时,您提供的密码是您要用于导出文件的密码,它不是源证书的密码。

I'm not sure what you can do with X509Store and password-protected certs because the password should be supplied to the X509Certificate constructor and you get already-instantiated objects out of the store. 我不确定你可以用X509Store和密码保护的证书做什么,因为密码应该提供给X509Certificate构造函数,你可以从商店中获取已经实例化的对象。

I think you can just get the raw data from the cert you want and construct a new one with the password you want. 您可以从您想要的证书中获取原始数据,并使用您想要的密码构建一个新数据。 For example: 例如:

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

I would also suggest you try to use SecureString when dealing with passwords (but that's a different bag of worms...) 我还建议你在处理密码时尝试使用SecureString (但那是SecureString不同的蠕虫......)

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

When the cert was imported into the certificate store, I think the key has to be marked as "exportable" otherwise I don't think you can export the private key..当证书被导入证书存储时,我认为密钥必须被标记为“可导出”,否则我认为你不能导出私钥..

在此处输入图片说明

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

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