2011-06-21 69 views
6

我需要在SSL证书的网页指纹中显示。 在PHP中可能吗?功能PHP SSL证书指纹

openssl_x509_parse 

不返回SHA1和MD5指纹。 如何解决这个问题? 谢谢。

回答

1

我猜最简单的方法将是通过系统

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

调用OpenSSL和是的,我知道,这是没有像这样做的干净的方式 - 但是,它是唯一一个我能想到我的头顶!

+0

恐怕如果使用system或exec - works会依赖于OS。为此,我尝试仅使用OpenSSL的PHP​​函数 –

13

我想你可以生成SHA指纹用下面的代码:

$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); 
} 
+0

非常适合我,谢谢。 –

4

这里是一个更好的解决方案:

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

从PHP 5.6起,您可以使用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 

这个功能目前无证,但是这将固定在释放时间;这是函数签名:

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