Search code examples
c#securityx509certificatex509certificate2

C# Loading Certificate requiring password


I have below code, when there is only one certificate, I can select the certificate, and if there is more than 1 certificate and I will ask the user to choose the certificate by calling

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

One thing I noticed that is when there is only once certificate, I don't need to type password which is expected because I used that certificate to login from my computer; but have multiple certificate, I have to type password for that and I don't want to (because I have already typed the password when I login to windows system); any help/idea is appreciated.

Full Code Snippet:

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;

Solution

  • well, it depends on the state of certificate.