MarioDS
MarioDS

Reputation: 13063

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?

Upvotes: 8

Views: 7522

Answers (1)

Rob
Rob

Reputation: 27357

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);
}

Upvotes: 14

Related Questions