PHP openssl_verify() Function
Last Updated :
27 Oct, 2021
The openssl_verify() function is an inbuilt function in PHP which is used to verifies that if the signature is correct for the specified data using the public key associated with public_key or not. This must be the public key corresponding to the private key used for signing.
Syntax:
openssl_verify( $data, $signature,
$public_key, $algorithm ): int|false
Parameters: This function accept four parameters which are listed below –
- data: The string of data used to generate the signature previously.
- signature: A raw binary string, generated by openssl_sign() or similar means.
- public_key: string – a PEM formatted key, example, “—–BEGIN PUBLIC KEY—– MIIBCgK…”
- algorithm: A valid string returned by openssl_get_md_methods() function.
Return Value: It returns 1 if the signature is correct, 0 if it is incorrect, and -1 or false on error.
Note: The public key comes from a certificate in any of the support formats.
Listed below are examples illustrating the use of openssl_verify() function:
Example 1:
PHP
<?php
$data = 'geeks for geeks' ;
$private_key_rsa = openssl_pkey_new( array (
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details( $private_key_rsa );
$public_key_rsa = openssl_pkey_get_public( $details [ 'key' ]);
openssl_sign( $data , $signature ,
$private_key_rsa , "sha256WithRSAEncryption" );
$result = openssl_verify( $data , $signature ,
$public_key_rsa , OPENSSL_ALGO_SHA256);
if ( $result == 1) {
echo "signature is valid for given data." ;
} elseif ( $ok == 0) {
echo "signature is invalid for given data." ;
} else {
echo "error: " .openssl_error_string();
}
?>
|
Output:
signature is valid for given data.
Example 2:
PHP
<?php
$data = 'geeks for geeks' ;
$private_key_rsa = openssl_pkey_new( array (
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details( $private_key_rsa );
$public_key_rsa = openssl_pkey_get_public( $details [ 'key' ]);
openssl_sign( $data , $signature ,
$private_key_rsa , "sha256WithRSAEncryption" );
$data = 'geeks and geeks' ;
$result = openssl_verify( $data , $signature ,
$public_key_rsa , OPENSSL_ALGO_SHA256);
if ( $result == 1) {
echo "signature is valid for given data." ;
} elseif ( $ok == 0) {
echo "signature is invalid for given data." ;
} else {
echo "error: " .openssl_error_string();
}
?>
|
Output:
signature is invalid for given data.
Reference: https://www.php.net/manual/en/function.openssl-verify.php
Share your thoughts in the comments
Please Login to comment...