0

I have generated a X509 certificate in DER format, which is stored in a file with the name cert.crt.

I would like to be able to hash it with sha256 algorithm.

How can this be done ?

I already have a function that allows me to hash any buffer of data, but I have the certificate in a file. Is there an easy way to do this ?

I am looking for a C implementation.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
mmm
  • 689
  • 2
  • 12
  • 25
  • Topic says PEM, but question text says DER. Which format is it? – thuovila May 16 '13 at 11:19
  • Why would you need to hash a certificate? Certificate already has a signature that includes a hash. If you need certificate validation, then it's much more complicated process than just "hashing a certificate". – Eugene Mayevski 'Callback May 16 '13 at 17:38

3 Answers3

0

Take a look at functions fopenand fread, they will help you.

João Fernandes
  • 1,101
  • 5
  • 11
0

Maybe http://linux.die.net/man/3/pem_read_x509 or http://linux.die.net/man/3/d2i_x509_fp can help you. Though the SSL man pages are terse, to put it nicely. In case the documentation fails, look for examples in the openssl utilitys source code.

Edit Also look at other SO answers, e.g. Extract pem certificate information programmatically using openssl and Is a X509 certificate in DER format ASN1 encoded?

Community
  • 1
  • 1
thuovila
  • 1,960
  • 13
  • 21
0

For counting fingerprint hash of a PEM certificate file:

FILE *fp = fopen(pem_file_path, "r");
if (fp)
{
    X509 *x509 = PEM_read_X509(fp, NULL, NULL, NULL);
    if (x509)
    {
        unsigned char md[EVP_MAX_MD_SIZE];
        
        if (X509_digest(x509, EVP_sha256(), md, NULL) == 1)
        {
            // ok
        }
        
        X509_free(x509);
    }   
    fclose(fp);
}

Result should be same as with command:

openssl x509 -in my.pem -noout -fingerprint -sha256

For changing the hash algorithm just change EVP_sha256() by EVP_sha512(), EVP_sha1() etc...

SKi
  • 8,007
  • 2
  • 26
  • 57