You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.7 KiB
PHP
61 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Helper\Baofu;
|
|
|
|
use Exception;
|
|
|
|
class SignatureUtil
|
|
{
|
|
|
|
/**
|
|
*
|
|
* @param string $data 原数据
|
|
* @param string $pfxPath 私钥路径
|
|
* @param string $pwd 私钥密码
|
|
* @return string
|
|
* @throws Exception
|
|
*/
|
|
public static function sign($data, $pfxPath, $pwd)
|
|
{
|
|
if(!file_exists($pfxPath)) {
|
|
throw new Exception('私钥文件不存在!');
|
|
}
|
|
|
|
$pkcs12 = file_get_contents($pfxPath);
|
|
$pfxPathStr = [];
|
|
if (openssl_pkcs12_read($pkcs12, $pfxPathStr, $pwd)) {
|
|
$privateKey = $pfxPathStr['pkey'];
|
|
$binarySignature = null;
|
|
if (openssl_sign($data, $binarySignature, $privateKey, OPENSSL_ALGO_SHA1)) {
|
|
return bin2hex($binarySignature);
|
|
} else {
|
|
throw new Exception('加签异常!');
|
|
}
|
|
} else {
|
|
throw new Exception('私钥读取异常【密码和证书不匹配】!');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 验证签名自己生成的是否正确
|
|
*
|
|
* @param string $data 签名的原文
|
|
* @param string $cerPath 公钥路径
|
|
* @param string $signature 签名
|
|
* @return bool
|
|
* @throws Exception
|
|
*/
|
|
public static function verifySign($data, $cerPath, $signature)
|
|
{
|
|
if(!file_exists($cerPath)) {
|
|
throw new Exception('公钥文件不存在!路径:' . $cerPath);
|
|
}
|
|
$pubKey = file_get_contents($cerPath);
|
|
$certs = openssl_get_publickey($pubKey);
|
|
$ok = openssl_verify($data, hex2bin($signature), $certs);
|
|
if ($ok == 1) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
} |