I'm currently working on an app, which uses the openssl library (libcrypto) to generate certificates. Now I have to get the hash of a already existing certificate.
When I use my Terminal I am able to generate the hash value by using
openssl x509 -hash -in cert.pem -noout
Output: 01da0e2b
This is my code where I try t generate my hash value by using the library in C.
X509 *cert = NULL;
FILE *fp = fopen(currentCert.UTF8String, "r");
PEM_read_X509(fp, &cert, NULL, NULL);
long hash = X509_subject_name_hash(cert);
char *mdString = malloc(sizeof(long));
sprintf(mdString, "%lx",hash);
printf(mdString);
Output: 1817886a
But actually my output is a different one. Has anybody an idea what am I doing wrong ?
You are not allocating enough memory for the string, although I can't be sure that is the cause of your problem.
will allocate 4 bytes to the string, yet it clearly needs to hold 8 bytes plus a terminator, so I suggest
Here's how OpenSSL uses it...
Then, looking at
apps/x509.c
:And your declaration should be:
Then:
Also, OpenSSL changed the way in calculates the subject hash sometime around OpenSSL 1.0.1. That's why there is an
X509_subject_name_hash
andX509_subject_name_hash_old
.If you are using or comparing against OpenSSL 0.9.8 (on, say Mac OS X 10), then see Generate Subject Hash of X509Certificate in Java. Though its Java, it details OpenSSL handling of the subject hash.