How do I read the Common Name from the client certificate?

Sinaesthetic picture Sinaesthetic · Sep 5, 2014 · Viewed 14.3k times · Source

Our application needs a piece of data that it is included in the client cert's common name. Currently, I'm trying to get it from HttpContext.Current.Request.ClientCertificate. How do I read this out? Sadly, I'm trying to code this blind while I figure out why SoapUI isn't sending the cert, so I haven't tried much other than reading about the object on MSDN and poking through the empty properties but I'm not sure what I'm looking for. So to recap, what do I need to do to pull out the common name from this cert? TIA

Answer

Yew Hong Tat picture Yew Hong Tat · May 7, 2015

I am maybe too late to answer your question but i hope this would help others who are looking for the way to get common name from certificate.

If you use 'Subject', you might need to trim away other unnecessary information. For example, CN = localhost,OU = DepartmentName,O = CompanyName,L = Location,S = State,C = Country

Dim store As New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.ReadOnly)
store.Certificates(0).Subject

But if you use the code below, you will get 'localhost' which directly give you the common name of the certificate.

Dim store As New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.ReadOnly)
store.Certificates(0).GetNameInfo(X509NameType.SimpleName, False)

Here's the link for reference:- https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.getnameinfo(v=vs.110).aspx