PHP SSL Certificate Fingerprint

2019-04-26 21:23发布

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.

5条回答
淡お忘
2楼-- · 2019-04-26 21:48

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楼-- · 2019-04-26 21:57

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 ] ] )
查看更多
We Are One
4楼-- · 2019-04-26 21:58

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!!!

查看更多
Summer. ? 凉城
5楼-- · 2019-04-26 22:06

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);
 }
查看更多
beautiful°
6楼-- · 2019-04-26 22:11

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

Use as your starting point to bake your own viewer.

查看更多
登录 后发表回答