php 公钥加密,私钥解密 & 私钥加签,公钥验签

该代码类实现了RSA算法的公钥加密、私钥解密以及私钥加签和公钥验签的功能。使用openssl库进行操作,涉及的关键函数包括openssl_pkey_get_public、openssl_private_decrypt等,确保数据的安全传输与验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
/*
* 公钥加密,私钥解密
* 私钥加签,公钥验签
*/
class Ga
{
    const RSA_ENCRYPT_BLOCK_SIZE = 245;//117;//加密切割长度

    const RSA_DECRYPT_BLOCK_SIZE = 256;//128;//解密切割长度

    
    public $gy = 'xxx.cer';//公钥
    public $sy = 'xxx.pfx';//私钥
    public $sy_pwd='xxx';//私钥密码
    

    //加密
    public function encrypt_new($content)
    {
        $path=storage_path($this->gy);
        $certificate = file_get_contents($path);
        $key = openssl_pkey_get_public($certificate);
        
        $result='';

        $data = str_split($content, self::RSA_ENCRYPT_BLOCK_SIZE);

        foreach ($data as $block) {

            openssl_public_encrypt($block, $dataEncrypt, $key, OPENSSL_PKCS1_PADDING);

            $result .= $dataEncrypt;
        
        }
        return $result ? base64_encode($result) : null;
    }
    //解密
    
    public function decrypt_new($string)
    {
        $file_path=storage_path($this->sy);
        $certs = array();
        openssl_pkcs12_read(file_get_contents($file_path), $certs, $this->sy_pwd);
        
        $encrypted = base64_decode($string);
        //分段解密
        $result = '';
        $data = str_split($encrypted, self::RSA_DECRYPT_BLOCK_SIZE);
        foreach ($data as $block) {
            openssl_private_decrypt($block, $decrypted, $certs['pkey'],OPENSSL_PKCS1_PADDING);
            
            $result .= $decrypted;
        }
        return $result ? $result : null;
    }
    
    //加签
    public function sign_new($encrypted)
    {
        
        $file_path = storage_path($this->sy);
        $certs = array();
        openssl_pkcs12_read(file_get_contents($file_path), $certs,$this->sy_pwd);
        $signature = '';
        $result = openssl_sign($encrypted, $signature, $certs['pkey'], OPENSSL_ALGO_SHA256);
        if (!$result) {
            return false;
        }
        return base64_encode($signature);

    }
    
    //验签
    public function verify($data,$sign)
    {
        $cert_path = storage_path($this->gy);
        $source = openssl_pkey_get_public(file_get_contents($cert_path));
        $res=openssl_verify($data, $sign, $source,OPENSSL_ALGO_SHA256);      // 1:验签通过,0:验签失败,-1:系统内部错误
        return $res;
    }
}
    ```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值