2048位RSA非对称密钥加密

快速获取RSA密钥对:http://www.metools.info/code/c80.html

示例代码:

<?php

class App extends BaseController
{
    private $syncUrl = 'https://www.xxx.com/api/event/sync';

    private $privateKey; //私钥
    private $publicKey; //其他系统公钥

    private $keyLen = 2048;
    private $appId = 1;
    private $identity = 'hello';


    public function __construct()
    {
        $this->privateKey = file_get_contents((app()->getRootPath() . 'private_key.pam'));
        $this->publicKey = file_get_contents((app()->getRootPath() . 'cert_public.pam'));
    }

    //新版接口
    public function test($uid='', $token='')
    {
        //请求tokenIsValidSync判断请求是否合法
        $data = [
            'app_id'=>$this->appId,
            'app_identity'=>$this->identity,
            'timestamp'=>time(),
            'rnd_str'=>uniqid(),
            'event'=>'tokenIsValidSync',
            'uid'=>$uid,
            'token'=>$token,
            'profile'=>1
        ];
        $enData = $this->privateEncrypt($data);

        $postData = [
            'app_id'=>$this->appId,
            'data'=>$enData
        ];

        $ret = HttpService::postRequest($this->syncUrl, $postData);
        $info = json_decode($ret, true);
        $decryptData = $this->publicDecrypt($info['data']);
        $userInfo = json_decode($decryptData, true);
    }

    /**
     * 私钥加密
     *
     * @param string|array $data 待加密数据
     * @return string 已加密的内容
     */
    public function privateEncrypt($data)
    {
        //如果是数组,则转换为JSON字符串
        if (is_array($data)) $data = json_encode($data);
        if (!is_string($data)) {
            return null;
        }

        $encrypted = '';
        //采用默认的 OPENSSL_PKCS1_PADDING 填充格式,数据长度必须小于密钥长度 - 11
        $part_len = $this->keyLen / 8 - 11;
        $parts = str_split($data, $part_len);

        foreach ($parts as $part) {
            $encrypted_temp = '';
            openssl_private_encrypt($part, $encrypted_temp, $this->privateKey);
            $encrypted .= $encrypted_temp;
        }

        return base64_encode($encrypted);
    }

    /**
     * 公钥解密
     *
     * @param string $encrypted 待解密内容
     * @return string 已解密内容
     */
    public function publicDecrypt($encrypted = '')
    {
        if (!is_string($encrypted)) {
            return null;
        }

        $decrypted = '';
        $part_len = $this->keyLen / 8;
        $base64_decoded = base64_decode($encrypted);
        $parts = str_split($base64_decoded, $part_len);

        foreach ($parts as $part) {
            $decrypted_temp = '';
            openssl_public_decrypt($part, $decrypted_temp, $this->publicKey);
            $decrypted .= $decrypted_temp;
        }

        return $decrypted;
    }


}

Tags: 加密

添加新评论