question

csharpuser12345-3892 avatar image
0 Votes"
csharpuser12345-3892 asked $$ANON_USER$$ edited

Certificate Issue

Dear All,


Using C# how can we retrieve certificate from a certificate store by Common Name


Any help would be greatly appreciated

dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

APoblacion avatar image
0 Votes"
APoblacion answered APoblacion edited

The certificate does not have a specific field for "common name". Instead, it is typical to store the common name in the subject name field of the certificate. If your certificate is configured in this way, then you perform a search by subject name, passing the common name as an argument:

             X509Certificate2Collection certCollection;
             using (X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine))
             {
                 certStore.Open(OpenFlags.ReadOnly);
                 certCollection = certStore.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false);
                 certStore.Close();
             }

The certCollection will return all the certificates that are found, which could be more than one because the Subject Name does not force any uniqueness limitations. So you then have to loop over all the certificates returned in the collection examining other properties of the certificate (such as the expiration date) until you find the one you want.

EDIT: Link to documentation.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.