TP5 RSA加解密!

<?php
/**
 * Created by PhpStorm.
 * User: zhangHong
 * Date: 2019/7/18
 * Time: 9:54
 */

namespace app\common\controller;

class Encryption {

    private $publicKey;

    private $privateKey;

    private $keyLength;


    /**
     * 初始化
     *
     */
    public function __construct(){
        $this->publicKey  = Config("encryption")['rsa']['publicKey'];
        $this->privateKey = Config("encryption")['rsa']['privateKey'];

        // 公钥
        $publicId         = openssl_pkey_get_public($this->publicKey);
        $this->keyLength  = openssl_pkey_get_details($publicId)['bits'];

        // 私钥
        $privateId        = openssl_pkey_get_private($this->privateKey);
        $this->keyLength  = openssl_pkey_get_details($privateId)['bits'];
    }


    /**
     * 生成签名
     *
     * @param string 签名材料
     * @param string 签名编码(base64/hex/bin)
     * @return 签名值
     */
    public function sign($data, $code = 'base64'){
        $ret = false;
        $privateId = openssl_get_privatekey($this->privateKey);
        if (openssl_sign($data, $ret, $privateId)){
            $ret = $this->encodeSign($ret, $code);
        }

        return $ret;
    }


    /**
     * 验证签名
     *
     * @param string 签名材料
     * @param string 签名值
     * @param string 签名编码(base64/hex/bin)
     * @return bool
     */
    public function verify($data, $sign, $code = 'base64'){
        $ret = false;
        $sign = $this->decodeSign($sign, $code);
        if ($sign !== false) {
            $publicId = openssl_get_publickey($this->publicKey);
            switch (openssl_verify($data, $sign, $publicId)){
                case 1: $ret = true; break;
                case 0:
                case -1:
                default: $ret = false;
            }
        }

        return $ret;
    }


    /**
     * 加密
     *
     * @param string 明文
     * @param string 密文编码(base64/hex/bin)
     * @param int 填充方式(貌似php有bug,所以目前仅支持OPENSSL_PKCS1_PADDING)
     * @return string 密文
     */
    public function encrypt($data, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING){
        $ret = false;
        if (!$this->checkPadding($padding, 'en')) $this->errorInfo('padding error');
        if (openssl_public_encrypt($data, $result, $this->publicKey, $padding)){
            $ret = $this->encodeSign($result, $code);
        }
        return $ret;
    }


    /**
     * 解密
     *
     * @param string 密文
     * @param string 密文编码(base64/hex/bin)
     * @param int 填充方式(OPENSSL_PKCS1_PADDING / OPENSSL_NO_PADDING)
     * @param bool 是否翻转明文(When passing Microsoft CryptoAPI-generated RSA cyphertext, revert the bytes in the block)
     * @return string 明文
     */
    public function decrypt($data, $code = 'base64', $padding = OPENSSL_PKCS1_PADDING, $rev = false){
        $ret = false;
        $data = $this->decodeSign($data, $code);
        if (!$this->checkPadding($padding, 'de')) $this->errorInfo('padding error');
        if ($data !== false){
            if (openssl_private_decrypt($data, $result, $this->privateKey, $padding)){
                $ret = $rev ? rtrim(strrev($result), "\0") : ''.$result;
            }
        }
        return $ret;
    }


    /**
     * 获取key信息
     * @return array
     */
    public function getKeyInfo() {
        $result = [
            "publicInfo" => [
                "publicKey" => $this->publicKey,
                "keyLength" => $this->keyLength,
            ],
            "privateInfo" => [
                "privateKey" => $this->privateKey,
                "keyLength"  => $this->keyLength,
            ],
        ];

        return $result;
    }

    /***************************************************** 私有方法 ****************************************************/

    /**
     * 检测填充类型
     * 加密只支持PKCS1_PADDING
     * 解密支持PKCS1_PADDING和NO_PADDING
     *
     * @param int 填充模式
     * @param string 加密en/解密de
     * @return bool
     */
    private function checkPadding($padding, $type){
        if ($type == 'en'){
            switch ($padding){
                case OPENSSL_PKCS1_PADDING:
                    $ret = true;
                    break;
                default:
                    $ret = false;
            }
        } else {
            switch ($padding){
                case OPENSSL_PKCS1_PADDING:
                case OPENSSL_NO_PADDING:
                    $ret = true;
                    break;
                default:
                    $ret = false;
            }
        }
        return $ret;
    }


    /**
     * 加码
     * @param $data
     * @param $code
     * @return bool|string
     */
    private function encodeSign($data, $code){
        switch (strtolower($code)){
            case 'base64':
                $data = base64_encode(''.$data);
                break;
            case 'hex':
                $data = bin2hex($data);
                break;
            case 'bin':
            default:
        }
        return $data;
    }


    /**
     * 解码
     * @param $sign
     * @param $code
     * @return bool|string
     */
    private function decodeSign($sign, $code){
        $data = false;
        switch (strtolower($code)){
            case 'base64':
                $data = base64_decode($sign);
                break;
            case 'hex':
                $data = $this->hex2Bin($sign);
                break;
            case 'bin':
            default:
        }
        return $data;
    }


    /**
     * 自定义错误处理
     * @param $msg
     */
    private function errorInfo($msg){
        die('RSA Error:' . $msg);
    }

    /**
     * hex2Bin
     * @param bool $hex
     * @return bool|string
     */
    private function hex2Bin($hex = false){
        $ret = $hex !== false && preg_match('/^[0-9a-fA-F]+$/i', $hex) ? pack("H*", $hex) : false;
        return $ret;
    }


    /**
     * sha256 加密
     * @param $data
     * @param bool $rawOutput
     * @return bool|string
     */
    public function sha256($data, $rawOutput = false) {
        if (!is_scalar($data)) {
            return false;
        }

        $data = (string)$data;
        $rawOutput = !!$rawOutput;

        return hash('sha256', $data, $rawOutput);
    }
}

在线生成秘钥:http://web.chacuo.net/netrsakeypair

THE END