8

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.

Wikinaut
  • 113
  • 1
  • 5
Lorenzo Manucci
  • 850
  • 2
  • 14
  • 28

5 Answers5

14

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);
}
Remco Tolsma
  • 141
  • 3
5

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);
 }
Mike
  • 1,992
  • 4
  • 31
  • 42
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 ] ] )
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
3

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

Mez
  • 24,430
  • 14
  • 71
  • 93
0

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

Use as your starting point to bake your own viewer.

Wikinaut
  • 113
  • 1
  • 5