RSACrypt.php 1.06 KB
<?php

namespace common\exts;

class RSACrypt
{
    private $pubkey;
    private $privkey;

    /**
     * RSACrypt constructor.
     * @param null $privateKey
     * @param null $publicKey
     */
    function __construct($privateKey = null, $publicKey = null)
    {
        // 获得资源类型公钥和私钥,
        $this->privkey = openssl_pkey_get_private($privateKey);
        $this->pubkey = openssl_pkey_get_public($publicKey);
    }

    /**
     * 加密
     * @param $data
     * @return string
     */
    public function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey)) {
            $data = base64_encode($encrypted);
            return $data;
        } else {
            return null;
        }
    }

    /**
     * 解密
     * @param $data
     * @return mixed
     */
    public function decrypt($data)
    {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey)) {
            $data = $decrypted;
            return $data;
        } else {
            return null;
        }
    }
}