Lorenzo Manucci
Lorenzo Manucci

Reputation: 880

PHP SSL Certificate Fingerprint

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.

Upvotes: 9

Views: 7652

Answers (5)

Ja͢ck
Ja͢ck

Reputation: 173562

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 ] ] )

Upvotes: 4

Wikinaut
Wikinaut

Reputation: 113

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

Use as your starting point to bake your own viewer.

Upvotes: 0

Mike
Mike

Reputation: 2012

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);
 }

Upvotes: 5

Remco Tolsma
Remco Tolsma

Reputation: 151

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);
}

Upvotes: 15

Mez
Mez

Reputation: 24933

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

Upvotes: 3

Related Questions