php使用签名与验签

2021-09-11
/**
 * @description: 签名与验签
 */
class Sign
{

    /**
     * @description: 支持的算法,同一个数组中的算法名,写法不同,实际相同,签名及验签时可以分别传参
     * @var array
     */
    public static $algorithms = [
            ['MD4', 'md4WithRSAEncryption'],
            ['MD5', 'md5WithRSAEncryption'],
            ['RIPEMD160', 'ripemd160WithRSA', 'rmd160', 'ripemd'],
            ['SHA1', 'sha1WithRSAEncryption'],
            ['SHA224', 'sha224WithRSAEncryption'],
            ['SHA256', 'sha256WithRSAEncryption'],
            ['SHA384', 'sha384WithRSAEncryption'],
            ['SHA512', 'sha512WithRSAEncryption'],
        ];
        
    /**
     * @description: 使用私钥签名
     * @param string $data 需要签名的数据
     * @param mixed $private_key 私钥资源、字符串
     * @param string|int $algorithm 签名算法,openssl_get_md_methods()之一
     * @return string base64Encode的字符串
     */
    public static function signData($data, $private_key, $algorithm = OPENSSL_ALGO_SHA1): string
    {
        if (!openssl_sign($data, $signature, $private_key, $algorithm)) {
            return static::errors(1);
        }
        return base64_encode($signature);
    }

    /**
     * @description: 使用公钥验证签名
     * @param string $data 验签的原始数据
     * @param string $signature 需要验签的数据,base64Encode的字符串
     * @param mixed $pub_key_id 公钥资源、字符串
     * @param string|int $algorithm 签名算法,openssl_get_md_methods()之一
     * @return int|string 正确返回1,错误返回0,报错返回错误信息
     */
    public static function verify($data, $signature, $pub_key_id, $algorithm = OPENSSL_ALGO_SHA1)
    {
        $result = openssl_verify($data, base64_decode($signature), $pub_key_id, $algorithm);
        if ($result < 0) {
            return static::errors(1);
        }
        return $result;
    }

    /**
     * @description: 获取openSSL库的错误,错误消息已被队列化,可以查询到多条错误信息,最后一个是最近的一个错误。
     * @param int type 1、返回最后一条 2、返回全部
     * @return string|array
     */
    public static function errors($type = 2)
    {
        if ($type == 1) {
            return openssl_error_string();
        }
        $result = [];
        while ($data = openssl_error_string() !== false) {
            $result[] = $data;
        }
        return $result;
    }
}

生成私钥:Certificate类

使用

SecretKey::genPrivateKey();
$pb = SecretKey::genPublicKeys(1)[0];

$sign = Sign::signData('123321', SecretKey::$privateKey, 'SHA256');
var_dump(Sign::verify('123321', $sign, $pb, 'sha256WithRSAEncryption' ));

 

{/if}