-->

PHP SSL Certificate Fingerprint

2019-04-26 21:54发布

问题:

I need display in web page fingerprints of SSL Certificate. Is it possible in PHP? The function

openssl_x509_parse

doesn't return SHA1 and MD5 fingerprints. How resolve this problem? Thanks.

回答1:

I'd guess the easiest way is going to be to call openssl through system

$fingerprint = str_replace("SHA1 Fingerprint=", '', system('openssl x509 -noout -in /path/to/your/cert.pem -fingerprint'));

And yes, I know, this is nothing like a clean way of doing this - however, it's the only one I can think of of the top of my head!!!



回答2:

I think you can generate the SHA fingerprint with the following code:

$resource = openssl_x509_read($certificate);

$fingerprint = null;
$output = null;

$result = openssl_x509_export($resource, $output);
if($result !== false) {
    $output = str_replace('-----BEGIN CERTIFICATE-----', '', $output);
    $output = str_replace('-----END CERTIFICATE-----', '', $output);

    $output = base64_decode($output);

    $fingerprint = sha1($output);
}


回答3:

Here is a better solution:

 function sha1_thumbprint($file)
 {
    $file = preg_replace('/\-+BEGIN CERTIFICATE\-+/','',$file);
    $file = preg_replace('/\-+END CERTIFICATE\-+/','',$file);
    $file = trim($file);
    $file = str_replace( array("\n\r","\n","\r"), '', $file);
    $bin = base64_decode($file);
    return sha1($bin);
 }


回答4:

From PHP 5.6 onwards, you can use openssl_x509_fingerprint():

$cert = openssl_x509_read($certificate);
$sha1_hash = openssl_x509_fingerprint($cert); // sha1 hash
$md5_hash = openssl_x509_fingerprint($cert, 'md5'); // md5 hash

The function is currently undocumented, but this will be fixed at release time; this is the function signature:

openssl_x509_fingerprint($cert [, $hash_method = "sha1" [, $raw_output = false ] ] )


回答5:

Based on your information, I wrote a tiny certificate viewer in PHP

  • https://github.com/Wikinaut/MySimpleCertViewer

Use as your starting point to bake your own viewer.