php操作ssl,亲测可用

php 复制代码
<?php
/**
 * SSL/TLS 证书检测工具 (PHP版)
 * 功能:获取证书信息、TLS版本、加密套件、证书验证、HTTPS请求
 */

// ========== 获取网站证书信息 ==========
function get_certificate_info(string $hostname, int $port = 443): array {
    // 创建SSL上下文
    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true,
            'capture_peer_cert' => true
        ]
    ]);

    // 建立SSL连接
    $socket = @stream_socket_client(
        "ssl://$hostname:$port",
        $errno,
        $errstr,
        10,
        STREAM_CLIENT_CONNECT,
        $context
    );

    if (!$socket) {
        return ['error' => "连接失败: $errstr ($errno)"];
    }

    // 获取证书参数
    $params = stream_context_get_params($context);
    $cert = openssl_x509_parse($params['options']['ssl']['peer_cert']);
    openssl_x509_free($params['options']['ssl']['peer_cert']);
    fclose($socket);

    // 解析证书信息
    $info = [
        'subject' => $cert['subject'] ?? [],
        'issuer' => $cert['issuer'] ?? [],
        'version' => $cert['version'] ?? '',
        'serialNumber' => $cert['serialNumber'] ?? '',
        'notBefore' => date('Y-m-d H:i:s', $cert['validFrom_time_t']),
        'notAfter' => date('Y-m-d H:i:s', $cert['validTo_time_t']),
        'subjectAltName' => $cert['extensions']['subjectAltName'] ?? '',
        'daysUntilExpiry' => 0,
        'isExpiringSoon' => false
    ];

    // 计算剩余天数
    $expireTime = $cert['validTo_time_t'];
    $daysLeft = intval(($expireTime - time()) / 86400);
    $info['daysUntilExpiry'] = $daysLeft;
    $info['isExpiringSoon'] = $daysLeft < 30;

    return $info;
}

// ========== 获取TLS版本 ==========
function get_tls_version(string $hostname, int $port = 443): string {
    $context = stream_context_create(['ssl' => ['verify_peer' => true]]);
    $socket = @stream_socket_client("ssl://$hostname:$port", $_, $__, 10, STREAM_CLIENT_CONNECT, $context);
    if (!$socket) return '连接失败';

    $meta = stream_get_meta_data($socket);
    fclose($socket);
    return $meta['crypto']['protocol'] ?? '未知';
}

// ========== 获取加密套件 ==========
function get_cipher_info(string $hostname, int $port = 443): array {
    $context = stream_context_create(['ssl' => ['verify_peer' => true]]);
    $socket = @stream_socket_client("ssl://$hostname:$port", $_, $__, 10, STREAM_CLIENT_CONNECT, $context);
    if (!$socket) return ['错误' => '连接失败'];

    $meta = stream_get_meta_data($socket);
    fclose($socket);
    return [
        'cipher' => $meta['crypto']['cipher'] ?? '未知',
        'version' => $meta['crypto']['protocol'] ?? '未知',
        'bits' => $meta['crypto']['bits'] ?? '未知'
    ];
}

// ========== 验证证书 ==========
function verify_certificate(string $hostname, int $port = 443): array {
    $result = [
        'hostname' => $hostname,
        'valid' => false,
        'error' => null,
        'details' => []
    ];

    $context = stream_context_create([
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true,
            'capture_peer_cert' => true
        ]
    ]);

    $socket = @stream_socket_client("ssl://$hostname:$port", $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $context);

    if ($socket) {
        $params = stream_context_get_params($context);
        $cert = openssl_x509_parse($params['options']['ssl']['peer_cert']);
        $result['valid'] = true;
        $result['details'] = [
            'subject' => $cert['subject'] ?? [],
            'issuer' => $cert['issuer'] ?? [],
            'tls_version' => stream_get_meta_data($socket)['crypto']['protocol'] ?? '未知'
        ];
        fclose($socket);
    } else {
        $result['error'] = "证书验证失败: $errstr";
    }

    return $result;
}

// ========== 带证书校验的HTTPS请求 ==========
function https_request_with_cert_check(string $url): array {
    $result = [
        'url' => $url,
        'success' => false,
        'status_code' => null,
        'error' => null,
        'headers' => []
    ];

    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => 'User-Agent: PHP-SSL-Test',
            'timeout' => 10
        ],
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true
        ]
    ]);

    $response = @file_get_contents($url, false, $context);

    if ($response !== false) {
        $result['success'] = true;
        $result['status_code'] = 200;
        $result['headers'] = $http_response_header;
    } else {
        $error = error_get_last();
        $result['error'] = $error['message'] ?? '请求失败';
    }

    return $result;
}

// ========== 使用示例 ==========
$hostname = "www.google.com";

echo "=== 证书信息 ===\n";
$certInfo = get_certificate_info($hostname);
print_r("主题: " . json_encode($certInfo['subject']) . "\n");
print_r("颁发者: " . json_encode($certInfo['issuer']) . "\n");
echo "有效期至: {$certInfo['notAfter']}\n";
echo "剩余天数: {$certInfo['daysUntilExpiry']}\n";

echo "\n=== TLS版本 ===\n";
echo "TLS版本: " . get_tls_version($hostname) . "\n";

echo "\n=== 加密套件 ===\n";
$cipher = get_cipher_info($hostname);
echo "套件名称: {$cipher['cipher']}\n";
echo "协议版本: {$cipher['version']}\n";
echo "密钥位数: {$cipher['bits']}\n";

echo "\n=== 证书验证 ===\n";
$verify = verify_certificate($hostname);
echo "验证结果: " . ($verify['valid'] ? '通过' : '失败') . "\n";
if ($verify['error']) echo "错误: {$verify['error']}\n";
?>

<?php /** * SSL/TLS 证书检测工具 (PHP版) * 功能:获取证书信息、TLS版本、加密套件、证书验证、HTTPS请求 */ // ========== 获取网站证书信息 ========== function get_certificate_info(string hostname, int port = 443): array { // 创建SSL上下文 context = stream_context_create(\[ 'ssl' =\> \[ 'verify_peer' =\> true, 'verify_peer_name' =\> true, 'capture_peer_cert' =\> true \] \]); // 建立SSL连接 socket = @stream_socket_client( "ssl://hostname:port", errno, errstr, 10, STREAM_CLIENT_CONNECT, context ); if (!socket) { return ['error' => "连接失败: errstr (errno)"]; } // 获取证书参数 params = stream_context_get_params(context); cert = openssl_x509_parse(params['options']['ssl']['peer_cert']); openssl_x509_free(params\['options'\]\['ssl'\]\['peer_cert'\]); fclose(socket); // 解析证书信息 info = \[ 'subject' =\> cert['subject'] ?? [], 'issuer' => cert\['issuer'\] ?? \[\], 'version' =\> cert['version'] ?? '', 'serialNumber' => cert\['serialNumber'\] ?? '', 'notBefore' =\> date('Y-m-d H:i:s', cert['validFrom_time_t']), 'notAfter' => date('Y-m-d H:i:s', cert\['validTo_time_t'\]), 'subjectAltName' =\> cert['extensions']['subjectAltName'] ?? '', 'daysUntilExpiry' => 0, 'isExpiringSoon' => false ]; // 计算剩余天数 expireTime = cert['validTo_time_t']; daysLeft = intval((expireTime - time()) / 86400); info\['daysUntilExpiry'\] = daysLeft; info\['isExpiringSoon'\] = daysLeft < 30; return info; } // ========== 获取TLS版本 ========== function get_tls_version(string hostname, int port = 443): string { context = stream_context_create(['ssl' => ['verify_peer' => true]]); socket = @stream_socket_client("ssl://hostname:port", , __, 10, STREAM_CLIENT_CONNECT, context); if (!socket) return '连接失败'; meta = stream_get_meta_data(socket); fclose(socket); return meta\['crypto'\]\['protocol'\] ?? '未知'; } // ========== 获取加密套件 ========== function get_cipher_info(string hostname, int port = 443): array { context = stream_context_create(['ssl' => ['verify_peer' => true]]); socket = @stream_socket_client("ssl://hostname:port", , __, 10, STREAM_CLIENT_CONNECT, context); if (!socket) return \['错误' =\> '连接失败'\]; meta = stream_get_meta_data(socket); fclose(socket); return [ 'cipher' => meta\['crypto'\]\['cipher'\] ?? '未知', 'version' =\> meta['crypto']['protocol'] ?? '未知', 'bits' => meta\['crypto'\]\['bits'\] ?? '未知' \]; } // ========== 验证证书 ========== function verify_certificate(string hostname, int port = 443): array { result = [ 'hostname' => hostname, 'valid' =\> false, 'error' =\> null, 'details' =\> \[\] \]; context = stream_context_create([ 'ssl' => [ 'verify_peer' => true, 'verify_peer_name' => true, 'capture_peer_cert' => true ] ]); socket = @stream_socket_client("ssl://hostname:port", errno, errstr, 10, STREAM_CLIENT_CONNECT, context); if (socket) { params = stream_context_get_params(context); cert = openssl_x509_parse(params\['options'\]\['ssl'\]\['peer_cert'\]); result['valid'] = true; result\['details'\] = \[ 'subject' =\> cert['subject'] ?? [], 'issuer' => cert\['issuer'\] ?? \[\], 'tls_version' =\> stream_get_meta_data(socket)['crypto']['protocol'] ?? '未知' ]; fclose(socket); } else { result['error'] = "证书验证失败: errstr"; } return result; } // ========== 带证书校验的HTTPS请求 ========== function https_request_with_cert_check(string url): array { result = [ 'url' => url, 'success' =\> false, 'status_code' =\> null, 'error' =\> null, 'headers' =\> \[\] \]; context = stream_context_create([ 'http' => [ 'method' => 'GET', 'header' => 'User-Agent: PHP-SSL-Test', 'timeout' => 10 ], 'ssl' => [ 'verify_peer' => true, 'verify_peer_name' => true ] ]); response = @file_get_contents(url, false, context); if (response !== false) { result\['success'\] = true; result['status_code'] = 200; result\['headers'\] = http_response_header; } else { error = error_get_last(); result['error'] = error\['message'\] ?? '请求失败'; } return result; } // ========== 使用示例 ========== hostname = "www.google.com"; echo "=== 证书信息 ===\\n"; certInfo = get_certificate_info(hostname); print_r("主题: " . json_encode(certInfo['subject']) . "\n"); print_r("颁发者: " . json_encode(certInfo\['issuer'\]) . "\\n"); echo "有效期至: {certInfo['notAfter']}\n"; echo "剩余天数: {certInfo\['daysUntilExpiry'\]}\\n"; echo "\\n=== TLS版本 ===\\n"; echo "TLS版本: " . get_tls_version(hostname) . "\n"; echo "\n=== 加密套件 ===\n"; cipher = get_cipher_info(hostname); echo "套件名称: {cipher\['cipher'\]}\\n"; echo "协议版本: {cipher['version']}\n"; echo "密钥位数: {cipher\['bits'\]}\\n"; echo "\\n=== 证书验证 ===\\n"; verify = verify_certificate(hostname); echo "验证结果: " . (verify['valid'] ? '通过' : '失败') . "\n"; if (verify\['error'\]) echo "错误: {verify['error']}\n"; ?>

相关推荐
北漂Zachary3 小时前
四大编程语言终极对比
android·java·php·laravel
zuowei28894 小时前
华为网络设备配置文件备份与恢复(上传、下载、导出,导入)
开发语言·华为·php
学习使我健康7 小时前
Android App 启动原理
android·android studio
TechMix8 小时前
【性能工具】atrace、systrace、perfetto抓取的trace文件有何不同?
android·性能优化
张小潇8 小时前
AOSP15 WMS/AMS系统开发 - 窗口层级源码分析
android·前端
M1582276905510 小时前
工业 CAN 总线无线互联利器|4 路 CAN 转 4G/WiFi 网关 产品介绍
开发语言·php
努力努力再努力wz11 小时前
【MySQL入门系列】掌握表数据的 CRUD:DML 核心语法与执行逻辑解析
android·开发语言·数据结构·数据库·c++·b树·mysql
niucloud-admin12 小时前
PHP SAAS 框架常见问题——配置问题——地图配置报错
php
古月方枘Fry12 小时前
三层交换+VRRP实现负载
开发语言·网络·php
zh_xuan13 小时前
Android gradle任务
android·gradle构建