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
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Helper\Efps;
use App\Exception\BusinessException;
use App\Helper\StringHelper;
class Signer
{
protected static $env = 'prod';
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));
}
}