Friday, February 27, 2015

Comparing X509Certificate Subject with User Input


Recently I encountered an issue where I was comparing the certificate name of an X509Certificate with a user input.
The issue was that the subject a user would see on the certificate property has spaces in it
E.g. CN = xxx

However, when querying the subject of an X509Certificate2 object, it won’t have any spaces in it
E.g. CN=xxx

This would make the subject comparison fail
The fix was to use X500DistinguishedName for comparison of subject. Below is a snippet    

X509Certificate2 certificate = new X509Certificate2(@"xxx.cer");
// certificate.Subject results in CN=xxx
            X500DistinguishedName certificateSubjectname = new X500DistinguishedName(certificate.Subject);
            X500DistinguishedName configuredSubjectname = new X500DistinguishedName("CN = xxx");
            bool result = string.Equals(certificateSubjectname.Decode(X500DistinguishedNameFlags.None), configuredSubjectname.Decode(X500DistinguishedNameFlags.None), StringComparison.CurrentCulture);