证书的签名和验签经常用在和第三方对接接口的时候用到,用于身份校验和防止数据被篡改。下面整理了一个pfx格式的数字证书的签名和cer格式的公钥进行验签的过程。
tips:需要php开启openssl。
- 签名
/**
* 签名
*/
public static function sign($params, $keyPath, $pwd)
{
$params_str = arrToQuery($params, false);
$params_sha1x16 = sha1($params_str, false);
$private_key = self::getPrivateKey($keyPath, $pwd);
$isSignSucceed = openssl_sign($params_sha1x16, $signature, $private_key);
if ($isSignSucceed) {
$signature_base64 = base64_encode($signature);
$params ['signature'] = $signature_base64;
laRequest(">>>>>签名成功<<<<<<<");
} else {
laRequest(">>>>>签名失败<<<<<<<");
}
return $params;
}
function arrToQuery($arrayQuery, $urlEncode = true)
{
ksort($arrayQuery);
$tmp = array();
foreach ($arrayQuery as $k => $param) {
$tmp[] = $k . '=' . ($urlEncode ? urlencode($param) : $param);
}
$params = implode('&', $tmp);
return $params;
}
public static function getPrivateKey($keyPath, $pwd)
{
$pkcs12 = file_get_contents($keyPath);
openssl_pkcs12_read($pkcs12, $certs, $pwd);
return $certs ['pkey'];
}
- 验签
public static function verify($params , $pubkeyPath)
{
$signature_str = $params ['signature'];
$signature = base64_decode($signature_str);
unset ($params ['signature']);
$public_key = file_get_contents($pubkeyPath);
$params_str = arrToQuery($params, false);
$params_sha1x16 = sha1($params_str, false);
$isSuccess = openssl_verify($params_sha1x16, $signature, $public_key);
return $isSuccess;
}
function arrToQuery($arrayQuery, $urlEncode = true)
{
ksort($arrayQuery);
$tmp = array();
foreach ($arrayQuery as $k => $param) {
$tmp[] = $k . '=' . ($urlEncode ? urlencode($param) : $param);
}
$params = implode('&', $tmp);
return $params;
}