Search code examples
c#.netcertificateself-signedx509certificate2

How can I check if a certificate is self-signed?


I'm using C#.NET and need to install a bunch of certificates into the Windows certificate store.

I need to check which of those certificates are root certificates (i.e. self-signed), so I can install them into the "Trusted root certificates" store.

I'm using the standard X509Certificate2 class. My current idea is to check whether the Issuer and Subject are the same.

I've noticed that X509Certificate2 has Issuer - IssuerName and Subject - SubjectName.

Is it better to compare Issuer to Subject, or IssuerName to SubjectName? Or doesn't it really matter?

Also, is this a reliable method or would I be better off using another approach?


Solution

  • See this post: java - Find if a certificate is self signed or CA signed

    While it's not C#, the comment from the solution notes

    If the subject and issuer are the same, it is self-signed

    means you're correct about the way you're trying to validate it.

    IssuerName and SubjectName return a DistinguishedName which contains RawData (a byte[] containing the raw information for the issuer/subject). You'd be best off comparing this field, though I believe comparing Subject and Issuer is just as valid.

    So, you could write something like this:

    public static bool IsSelfSigned(X509Certificate2 cert)
    {
        return cert.SubjectName.RawData.SequenceEqual(cert.IssuerName.RawData);
    }