php之openssl相关

公钥加密解密

$sourceStr = "被加密的内容";
$public_key = "公钥";
$private_key = "私钥";
$key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap("公钥", 64, "\n", true) . "\n-----END PUBLIC KEY-----"; // 如果公钥格式非---BEGIN 开头需要这样处理
$encrypted = '';
$publicKey = openssl_get_publickey($key);// 私钥对应函数openssl_get_private
if (is_resource($publicKey)) {
    openssl_public_encrypt($sourceStr, $encrypted, $publicKey); 
    // 公钥加密, 对应私钥加密函数openssl_private_encrypt
    if ($encrypted) $encrypted = base64_encode($encrypted);
    openssl_free_key($publicKey);
}
echo $encrypted; // 加密后内容
$privateKey = openssl_get_private($private_key);
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey);
//私钥解密, 对应公钥解密函数openssl_public_decrypt

# 生成公钥密钥
$config = array(
        "digest_alg"       => "sha512",
        "private_key_bits" => 1024,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,
        "config"           => 'D:\xampp\apache\conf\openssl.cnf',// 指定openssl配置文件位置
        );
try {
    $res = openssl_pkey_new($config);
    $private_key = '';
    openssl_pkey_export($res, $private_key, null, $config);
    $details = openssl_pkey_get_details($res);
    $public_key = $details["key"];
} catch (Exception $e) {

}
if(!$private_key || !$public_key){
    _throw("get_encrypt_keys failed");
}
$result = array(
    'public_key' => $public_key,
    'private_key' => $private_key,
);
var_dump($result);

解析网站证书信息

# 获取证书信息
$context = stream_context_create(array(
    'ssl' => array(
        'capture_peer_cert' => true,
        'capture_peer_cert_chain' => true,
    )
));
$resource   = stream_socket_client($url, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
$cert       = stream_context_get_params($resource);
$ssl        = $cert['options']['ssl'];
$resource   = $ssl['peer_certificate'];
$ret        = array('crt' => '', 'pub' => '');
$pkey       = openssl_pkey_get_public($resource);
$ret['pub'] = openssl_pkey_get_details($pkey)['key'];
openssl_x509_export($resource, $pem);
$ret['crt'] = $pem;
foreach ($ssl['peer_certificate_chain'] as $resource) {
    openssl_x509_export($resource, $pem);
    $ret['crt'] .= "\n" . $pem;
}
$result = openssl_x509_parse($ret['crt']);
var_dump($result);

标签: none