C#加载需要密码的证书

C# Loading Certificate requiring password

我有下面的代码,当只有一个证书时,我可以select证书,如果有超过1个证书,我会要求用户通过调用[=12来选择证书=]

var certificates = X509Certificate2UI.SelectFromCollection(store.Certificates,
                "Digital Certificates", "Select a certificate from the following list:",
                X509SelectionFlag.SingleSelection);

我注意到一件事,当只有一次证书时,我不需要输入密码,因为我使用该证书从我的计算机登录;但是有多个证书,我必须为此输入密码,但我不想输入密码(因为我在登录 windows 系统时已经输入了密码);任何 help/idea 不胜感激。

完整代码片段:

X509Certificate2 certificate = null;

var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

    if (store.Certificates.Count == 1) {
        //Return the certificate present.
        certificate = store.Certificates[0];
    }
    else if (store.Certificates.Count > 0)
    {
        // Request the user to select a certificate 
        var certificates = X509Certificate2UI.SelectFromCollection(store.Certificates,
            "Digital Certificates", "Select a certificate from the following list:",
            X509SelectionFlag.SingleSelection);

        // Check if one has been returned
        if (certificates.Count == 1) {
            certificate = certificates[0];
        }
        else {
            throw new ArgumentException("Please select a certificate to publish PnL to Flash");
        }
    }
    else {
        throw new ArgumentException("There is no certificate available to publish PnL to flash, please contact support.");
    }
}
finally {
    store.Close();
}
return certificate;

嗯,这取决于证书的状态。