PHP SSL证书指纹

9
我需要在网页中显示SSL证书的指纹信息。PHP能实现吗?以下是相关函数:

openssl_x509_parse

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

15

我认为你可以使用以下代码生成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);
}

5
这里有一个更好的解决方案:
 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
从 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 ] ] )

3
我猜最简单的方法是通过系统调用openssl。
$fingerprint = str_replace("SHA1 Fingerprint=", '', system('openssl x509 -noout -in /path/to/your/cert.pem -fingerprint'));

是的,我知道,这并不是一种干净的方式来完成这个任务 - 但是,这是我能够想到的唯一的方法!!!


我担心如果使用system或exec,其工作将取决于操作系统。因此,我尝试仅使用PHP OpenSSL函数。 - Lorenzo Manucci

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接