How to extract the domain name out of an X509Certificate object during SslStream.AuthenticateAsClient? (.NET4)

billpg picture billpg · Dec 7, 2011 · Viewed 13.9k times · Source

I have a RemoteCertificateValidationCallback function called by SslStream.AuthenticateAsClient, which is passed an X509Certificate object.

I'd like to extract the name from that certificate, such that had I passed that string into AuthenticateAsClient, it would have passed. (Assuming no other issues.)

(Note: The Subject property contains the domain name, but it's inside a "CN=..., S=..." etc formatted string.)

See also: How to extract CN from X509Certificate in Java? (Asks a similar question for Java, but I can't find similar classes for .NET mentioned in those answers.)

(Followup to Eugene's answer.)
I've tried this...

var cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2();
cert2.Import(certificate.GetRawCertData());

... but cert2.SubjectName.Name still has the CN= etc formatting. Am I doing it wrong?

Answer

IMil picture IMil · Dec 24, 2012

I have done it the following way:

var cert2 = new X509Certificate2(cert);
string hostName = cert2.GetNameInfo(X509NameType.DnsName, false);

You may also check whether the certificate is valid:

bool valid = cert2.Verify();

(See this question for description of X509Certificate2 class)