Is serial number a unique key for X509 certificate?

isobretatel picture isobretatel · Feb 1, 2012 · Viewed 28.7k times · Source

Is certificate serial number a unique key for X509 certificate? User selects a certificate, and program stores serial number in preferences. Will the following code return the selected certificate?

public static X509Certificate2 GetCertificateBySerialNumber(string serialNumber)
{
    X509Certificate2 selectedCertificate = null;
    X509Store store = null;
    try
    {
        // get certificate from the store "My", "CurrentUser"
        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
        X509Certificate2Collection allCertificates = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection foundCertificates = (X509Certificate2Collection)allCertificates.Find(X509FindType.FindBySerialNumber, serialNumber, false);

        // select the first certificate in collection
        foreach (X509Certificate2 certificate in foundCertificates)
        {
            selectedCertificate = certificate;
            break;
        }
    }
    finally
    {
        if (store != null)
        {
            store.Close();
        }
    }

    return selectedCertificate;
}

UPDATE: I ended up using certificate thumbprint, as suggested by jglouie.

Answer

jglouie picture jglouie · Feb 1, 2012

No. For example, OpenSSL let's the user set this when they create certificates.

See: http://www.openssl.org/docs/apps/x509.html

-set_serial n specifies the serial number to use. This option can be used with either the -signkey or -CA options. If used in conjunction with the -CA option the serial number file (as specified by the -CAserial or -CAcreateserial options) is not used.

The serial number can be decimal or hex (if preceded by 0x). Negative serial numbers can also be specified but their use is not recommended.