PHP openssl_verify()函数
openssl_verify()函数是PHP中的一个内置函数,用于使用与public_key关联的公钥验证指定数据的签名是否正确。这必须是与用于签名的私钥对应的公钥。
句法:
openssl_verify( $data, $signature,
$public_key, $algorithm ): int|false
参数:此函数接受下面列出的四个参数 -
- data:先前用于生成签名的数据字符串。
- 签名:原始二进制字符串,由 openssl_sign() 或类似方式生成。
- public_key: 字符串 – PEM 格式的密钥,例如,“—–BEGIN PUBLIC KEY—– MIIBCgK…”
- 算法: openssl_get_md_methods()函数返回的有效字符串。
返回值:签名正确返回1,错误返回0,错误返回-1或false。
注意:公钥来自任何支持格式的证书。
下面列出的示例说明了 openssl_verify()函数的使用:
示例 1:
PHP
2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_rsa);
$public_key_rsa = openssl_pkey_get_public($details['key']);
// Create signature for your data
openssl_sign($data, $signature,
$private_key_rsa, "sha256WithRSAEncryption");
// Verify signature obtained for your data
$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();
}
?>
PHP
2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_rsa);
$public_key_rsa = openssl_pkey_get_public($details['key']);
// Create signature for your data
openssl_sign($data, $signature,
$private_key_rsa, "sha256WithRSAEncryption");
// Change the data
$data = 'geeks and geeks';
// Verify signature obtained for your data
$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();
}
?>
输出:
signature is valid for given data.
示例 2:
PHP
2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_rsa);
$public_key_rsa = openssl_pkey_get_public($details['key']);
// Create signature for your data
openssl_sign($data, $signature,
$private_key_rsa, "sha256WithRSAEncryption");
// Change the data
$data = 'geeks and geeks';
// Verify signature obtained for your data
$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();
}
?>
输出:
signature is invalid for given data.
参考: https://www. PHP.net/manual/en/函数.openssl-verify。 PHP