Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two X509Certificate2 c#

Tags:

c#

.net

winforms

How can I compare two X509Certificate2 objects?

I need to find whether two certificates are same. It's for user authentication purpose and I need to find if both the certificates are of the same person.

Can I use its serial number or thumprint properties? or is there any other methods?

Also I am new to this and would like to know is it safe to use X509Certificate for user authentication?

like image 366
Matt Avatar asked Jul 12 '12 10:07

Matt


2 Answers

A thumbprint is a unique value for the certificate, it is commonly used to find a particular certificate in a certificate store. More...

The serial number is a unique number issued by the certificate issuer. More...

like image 197
Yasser Shaikh Avatar answered Nov 06 '22 19:11

Yasser Shaikh


As @Rattle pointed out:

The Equals method should not be used when comparing certificates for security purposes. Instead, use a hash of the RawData property, or the Thumbprint property.


Late to the party (recently needed to compare two X509 certificates myself).

The X509Certificate class has an Equals() method:

Two objects are considered equal if they are X509Certificate objects and they have the same issuer and serial number.

using System;
using System.Security.Cryptography.X509Certificates;

public class X509
{

    public static void Main()
    {
        // The paths to the certificate signed files
        string Certificate =  @"Signed1.exe";
        string OtherCertificate = @"Signed2.exe";

        // Starting with .NET Framework 4.6, the X509Certificate type implements the IDisposable interface...
        using (X509Certificate certOne = X509Certificate.CreateFromCertFile(Certificate))
        using (X509Certificate certTwo = X509Certificate.CreateFromCertFile(OtherCertificate))
        {
            bool result = certOne.Equals(certTwo);

            Console.WriteLine(result);
        }
    }

}
like image 3
Mitch Wheat Avatar answered Nov 06 '22 20:11

Mitch Wheat