PHP openssl_pkey_get_public()函数用法及示例 - PHP教程

由网友 大卫 发布 阅读 2

PHP openssl_pkey_get_public()函数用法及示例 - PHP教程

PHP OpenSSL 函数手册

openssl_pkey_get_public()函数用于从证书中解析公钥,以供使用。

定义和用法

openssl_pkey_get_public()函数将返回您的公钥。

函数openssl_pkey_get_public()从给定证书中返回公钥,以便可以与其他函数一起使用。

语法

openssl_pkey_get_public ( mixed $certificate ) : resource

参数

序号参数描述
1

certificate

您可以使用以下证书:

1. X.509证书资源

2.来自文件的公钥,格式为file://path/to/file.pem。

3. PEM格式的公钥。

返回值

如果没有错误,PHP openssl_pkey_get_public()函数将返回一个正资源标识符。如果失败,它将返回false。

PHP版本

此函数将从大于5.0.0的PHP版本开始工作。

实例1

使用X.509证书的openssl_pkey_get_public()的工作-

<?php
   $dn = array(
      "countryName" => "IN",
		"stateOrProvinceName" => "Karnataka",
		"localityName" => "test1",
		"organizationName" => "test2",
		"organizationalUnitName" => "test3",
		"commonName" => "www.test.com",
		"emailAddress" => "xyz@test.com"
	);

       // 生成新的私钥/公钥对
	$privkey = openssl_pkey_new();

	// Generate a certificate
	$csr = openssl_csr_new($dn, $privkey, array('digest_alg' => 'sha256'));
	$res_cert = openssl_csr_sign($csr, null, $privkey, 365);
	openssl_x509_export($res_cert, $x_509_certificate);
	echo $res_pubkey = openssl_pkey_get_public($x_509_certificate);
?>

输出结果

Resource id #5

实例2

使用.pem文件的openssl_pkey_get_public()工作-

<?php
   $dn = array(
      "countryName" => "IN",
      "stateOrProvinceName" => "Karnataka",
      "localityName" => "test1",
		"organizationName" => "test2",
		"organizationalUnitName" => "test3",
		"commonName" => "www.test.com",
		"emailAddress" => "xyz@test.com"
   );

	//生成新的私钥/公钥对
	$privkey = openssl_pkey_new();

	//生成证书
	$csr = openssl_csr_new($dn, $privkey, array('digest_alg' => 'sha256'));
	$res_cert = openssl_csr_sign($csr, null, $privkey, 365);
	openssl_x509_export_to_file($res_cert, 'C:/xampp/htdocs/modules/openssl/x_509.pem');
	echo $res_pubkey = openssl_pkey_get_public(file_get_contents('C:/xampp/htdocs/modules/openssl/x_509.pem'));
?>

输出结果

Resource id #7

PHP OpenSSL 函数手册

PHP openssl_private_encrypt() PHP is_array()