PHP8 openssl_x509_verify

2024-03-13 11:25 更新

(PHP 7 >= 7.4.0, PHP 8)

openssl_x509_verify — 根据公钥验证x509证书的数字签名

说明

openssl_x509_verify(OpenSSLCertificate|string $certificate, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key): int

openssl_x509_verify() 验证证书是否由私有 密钥对应于公钥。certificatepublic_key

参数 

x509

参见密钥/证书参数以获取有效值列表。

public_key

OpenSSLAsymmetricKey - 一个密钥,由 openssl_get_publickey() 返回

string - PEM 格式的密钥(例如-----BEGIN PUBLIC KEY----- MIIBCgK...)

返回值 

如果签名正确,则返回 1,如果签名不正确,则返回 0,如果签名不正确,则返回 0,并且 错误时为 -1。

更新日志 

版本说明
8.0.0certificate现在接受 OpenSSLCertificate 实例; 以前,接受类型的资源。OpenSSL X.509
8.0.0public_key现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例; 以前,已接受 OR 类型的资源。OpenSSL keyOpenSSL X.509

示例 

示例 #1 openssl_x509_verify() example

<?php
$hostname = "news.php.net";
$ssloptions = array(
    "capture_peer_cert" => true, 
    "capture_peer_cert_chain" => true, 
    "allow_self_signed"=> false, 
    "CN_match" => $hostname,
    "verify_peer" => true,
    "SNI_enabled" => true,
    "SNI_server_name" => $hostname,
);
 
$ctx = stream_context_create( array("ssl" => $ssloptions) );
$result = stream_socket_client("ssl://$hostname:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx);
$cont = stream_context_get_params($result);
$x509 = $cont["options"]["ssl"]["peer_certificate"];
$certparsed = openssl_x509_parse($x509);

foreach($cont["options"]["ssl"]["peer_certificate_chain"] as $chaincert)
{
    $chainparsed = openssl_x509_parse($chaincert);
    $chain_public_key = openssl_get_publickey($chaincert);
    $r = openssl_x509_verify($x509, $chain_public_key);   
    if ($r==1)
    {
        echo $certparsed['subject']['CN'];
        echo " was digitally signed by ";
        echo $chainparsed['subject']['CN']."\n";
    }
}
?>

参见 

  • openssl_verify() - 验证签名
  • openssl_get_publickey() - 别名 openssl_pkey_get_public


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号