PHP - Function openssl_pkey_get_public()
Definition and Usage
The openssl_pkey_get_public() function will return you the public key.
Description
The function openssl_pkey_get_public() returns public key from the given certificate so that it can be used with other functions.
Syntax
openssl_pkey_get_public ( mixed $certificate ) : resource
Parameters
| Sr.No | Parameter | Description |
|---|---|---|
| 1 |
certificate |
You can make use of following certificates : 1. An X.509 certificate resource 2. Public key from the file in the format file://path/to/file.pem. 3. A PEM formatted public key. |
Return Values
PHP openssl_pkey_get_public() function returns a positive resource identifier if there is no error. It will return false if it fails.
PHP Version
This function will work from PHP Version greater than 5.0.0.
Example 1
Working of openssl_pkey_get_public() with X.509 certificate −
<?php
$dn = array(
"countryName" => "IN",
"stateOrProvinceName" => "Karnataka",
"localityName" => "test1",
"organizationName" => "test2",
"organizationalUnitName" => "test3",
"commonName" => "www.test.com",
"emailAddress" => "xyz@test.com"
);
// Generate a new private /public key pair
$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);
?>
This will produce following result −
Resource id #5
Example 2
Working of openssl_pkey_get_public() using .pem file −
<?php
$dn = array(
"countryName" => "IN",
"stateOrProvinceName" => "Karnataka",
"localityName" => "test1",
"organizationName" => "test2",
"organizationalUnitName" => "test3",
"commonName" => "www.test.com",
"emailAddress" => "xyz@test.com"
);
// Generate a new private /public key pair
$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_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'));
?>
This will produce following result −
Resource id #7