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.
payment/app/Helper/Efps/Signer.php

70 lines
1.9 KiB
PHTML

2 years ago
<?php
namespace App\Helper\Efps;
2 years ago
use App\Exception\BusinessException;
2 years ago
use App\Helper\StringHelper;
2 years ago
class Signer
{
1 year ago
protected static $env = 'prod';
2 years ago
private static function getConfig($key)
2 years ago
{
2 years ago
$config = Config::get(self::$env);
return $config ? ($config[$key] ?? null) : null;
2 years ago
}
2 years ago
2 years ago
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;
2 years ago
}
2 years ago
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;
2 years ago
}
2 years ago
2 years ago
public static function publicEncrypt($data)
2 years ago
{
2 years ago
//读取公钥文件
$pubKey = file_get_contents(self::getConfig('publicKeyFilePath'));
2 years ago
2 years ago
$res = openssl_get_publickey($pubKey);
if (empty($res)) {
throw new BusinessException('RSA公钥错误, 请检查公钥文件格式是否正确');
}
$crypttext = "";
1 year ago
openssl_public_encrypt($data,$crypttext, $res);
2 years ago
openssl_free_key($res);
return(base64_encode($crypttext));
}
2 years ago
}