摘要:写了一个用PHP生成PSA和RSA2算法签名和验签的工具类,在支付等接口方面通常会用到,下面是代码:class RSA2{
function rsaSign($data, $private_key, $sign_type=OPENSSL_ALGO_SHA256) {
$search = [
"-----BEGIN RSA PRIVATE KEY-----",
"-----END RSA PRIVATE KEY-----",
"\n",
"\r",
"\r\n"
];
$private_key = str_replace($search,"",$private_key);
$private_key = $search[0] . PHP_EOL . wordwrap($private_key, 64, "\n", true) . PHP_EOL . $search[1];
$res = openssl_get_privatekey($private_key);
if($res){
openssl_sign($data, $sign, $res, $sign_type);
openssl_free_key($res);
}else {
exit("私钥格式有误");
}
$sign = base64_encode($sign);
return $sign;
}
function rsaCheck($data, $public_key, $sign, $sign_type=OPENSSL_ALGO_SHA256) {
$search = [
"-----BEGIN PUBLIC KEY-----",
"-----END PUBLIC KEY-----",
"\n",
"\r",
"\r\n"
];
$public_key = str_replace($search,"",$public_key);
$public_key = $search[0] . PHP_EOL . wordwrap($public_key, 64, "\n", true) . PHP_EOL . $search[1];
$res = openssl_get_publickey($public_key);
if($res){
$result = (bool)openssl_verify($data, base64_decode($sign), $res);
openssl_free_key($res);
}else{
exit("公钥格式有误!");
}
return $result;
}
}
$str = 'yzmcms123456789';
echo '待签名的数据是:' . $str . '
';
$obj = new RSA2();
//生成RSA2签名
$sign = $obj->rsaSign($str, file_get_contents('private.txt'));
echo '签名后的数据是:' . $sign . '
';
//验签 RSA2
if($obj->rsaCheck($str, file_get_contents('public.txt'), $sign)){
echo '验证成功';
}else{
echo '验证失败';
}
默认签名方式为RSA(OPENSSL_ALGO_SHA256),如果使用RSA也比较简单只需要在调用签名和验签的方法里面多增加最后一个参数为OPENSSL_ALGO_SHA1就可以了,增加参数后执行的对应方法内的代码如下://签名 RSA
openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA1);
//验签 RSA
openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA1);