I'm working on a php program that will verify a digital signature. I'm testing with an example (valid) certificate, and decrypting the digital signature, this gives me the sha256 digest which I am trying to match:
$Cert1 = file_get_contents('CERT1/cert_array.json'); // TEST CERT DATA
$Cert1 = json_decode($Cert1, true);
$PublicKey = file_get_contents('CERT2/public_key_rsa.pem'); // CA CERT PUBLIC KEY
openssl_public_decrypt(hex2bin($Cert1['DigitalSignature']), $DecryptedDigitalSignature, $PublicKey, OPENSSL_PKCS1_PADDING); // DECRYPT SIGNATURE USING CA PUBLIC KEY
print('decrypted digital signature:' . bin2hex($DecryptedDigitalSignature) . "\n\n"); // PRINT RESULTS
This outputs the following:
decrypted digital signature:
3031300d0609608648016503040201050004200bf3dcf2340b972e97fe3c8493e11eeee01f298939734690d0b4e79e1f5701b4
There is some padding on the left, I now split this up to get the sha256 digest:
3031300d060960864801650304020105000420 // PADDING
0bf3dcf2340b972e97fe3c8493e11eeee01f298939734690d0b4e79e1f5701b4 // SHA256 DIGEST
Ok, so now I have my sha 256 digest, so I now wish to use the openssl_x509_fingerprint function on the same cert (CERT1) to create my own sha256 digest. This should match the digest that I already extracted from the cert from above. I use this code:
$Cert1 = file_get_contents('CERT1/cert.crt'); // THE CERT IN VALID x509 FORMAT
print(openssl_x509_fingerprint($Cert1, 'sha256'));
I get the following result:
d74157547fb287694b95b2533588c71f8706b0960e023fc4317f4f9a49ad2721
So, my question is, why am I getting "d74157547fb287694b95b2533588c71f8706b0960e023fc4317f4f9a49ad2721" and not "0bf3dcf2340b972e97fe3c8493e11eeee01f298939734690d0b4e79e1f5701b4"?
My Answer:
The reason you are getting different values for the sha256 digest from the openssl_x509_fingerprint function and the one you extracted manually is because openssl_x509_fingerprint function calculates the fingerprint of the entire certificate, not just the digital signature.
When you use openssl_x509_fingerprint function, it calculates the fingerprint of the entire certificate, including the public key, issuer information, validity period, etc. This is why the resulting sha256 digest is different from the one you extracted manually from the digital signature.
If you want to calculate the sha256 digest of just the digital signature, you will need to extract the digital signature from the certificate and then calculate the sha256 digest separately, as you have already done in your code.
In summary, the openssl_x509_fingerprint function calculates the fingerprint of the entire certificate, while you extracted the sha256 digest manually from just the digital signature. This is why you are getting different values.
Rate this post
4 of 5 based on 1386 votesComments