|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Helper\Efps;
|
|
|
|
|
|
|
|
|
|
use App\Exception\BusinessException;
|
|
|
|
|
use App\Helper\StringHelper;
|
|
|
|
|
|
|
|
|
|
class Signer
|
|
|
|
|
{
|
|
|
|
|
protected static $env = 'dev';
|
|
|
|
|
|
|
|
|
|
private static function getConfig($key)
|
|
|
|
|
{
|
|
|
|
|
$config = Config::get(self::$env);
|
|
|
|
|
return $config ? ($config[$key] ?? null) : null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static function sign($data) {
|
|
|
|
|
$certs = [];
|
|
|
|
|
openssl_pkcs12_read(
|
|
|
|
|
file_get_contents(self::getConfig('privateKeyFilePath')),
|
|
|
|
|
$certs,
|
|
|
|
|
self::getConfig('privateKeyPassword')
|
|
|
|
|
); //其中password为你的证书密码
|
|
|
|
|
|
|
|
|
|
if (empty($certs)) {
|
|
|
|
|
throw new BusinessException('请检查RSA私钥配置');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
openssl_sign($data, $sign, $certs['pkey'],OPENSSL_ALGO_SHA256);
|
|
|
|
|
$sign = base64_encode($sign);
|
|
|
|
|
return $sign;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static function verify($data, $sign) {
|
|
|
|
|
|
|
|
|
|
//读取公钥文件
|
|
|
|
|
$pubKey = file_get_contents(self::getConfig('publicKeyFilePath'));
|
|
|
|
|
|
|
|
|
|
$res = openssl_get_publickey($pubKey);
|
|
|
|
|
|
|
|
|
|
if (empty($res)) {
|
|
|
|
|
throw new BusinessException('RSA公钥错误, 请检查公钥文件格式是否正确');
|
|
|
|
|
}
|
|
|
|
|
//调用openssl内置方法验签,返回bool值
|
|
|
|
|
|
|
|
|
|
$result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
|
|
|
|
|
// 释放资源
|
|
|
|
|
openssl_free_key($res);
|
|
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static function publicEncrypt($data)
|
|
|
|
|
{
|
|
|
|
|
//读取公钥文件
|
|
|
|
|
$pubKey = file_get_contents(self::getConfig('publicKeyFilePath'));
|
|
|
|
|
|
|
|
|
|
$res = openssl_get_publickey($pubKey);
|
|
|
|
|
|
|
|
|
|
if (empty($res)) {
|
|
|
|
|
throw new BusinessException('RSA公钥错误, 请检查公钥文件格式是否正确');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$crypttext = "";
|
|
|
|
|
openssl_public_encrypt($data,$crypttext, $res );
|
|
|
|
|
openssl_free_key($res);
|
|
|
|
|
|
|
|
|
|
return(base64_encode($crypttext));
|
|
|
|
|
}
|
|
|
|
|
}
|