AESUtil.php 2.6 KB
<?php
/**
 * Created by PhpStorm.
 * User: ruidiudiu
 * Date: 2018/11/12
 * Time: 14:44
 */

namespace aesutil;

class AESUtil{
    private $key='';//秘钥的十六进制标识
    private $keyCrypt='';//加密后的16进制秘钥
    /**
     * @param string $_key 密钥
     */
    public function __construct($_key = '1111111111111111'){
        $hexKey = $this->stringToHex($_key);
        $k = $this->hexChr($hexKey);
        $this->key      = $k;
        $this->keyCrypt = $this->encrypt('',$k);
    }

    //进行指令加密
    public function encryption($stringHex){
        //填充0
        $stringHex=$this->zeroPadding($stringHex);
        //解析16进制字符
        $str = $this->hexChr($stringHex);
        //加密
        $encrypt=$this->encrypt($str,$this->key);
        //截取指令
        $instruction=substr($encrypt,0,strpos($encrypt,$this->keyCrypt));
        $data = $this->ToArray($instruction);
        return $data;
    }

    //进行指令解密
    public function decryption($stringHex){
        $crypt = $stringHex.$this->keyCrypt;
        $str   = $this->hexChr($crypt);
        $decrypt  = $this->decrypt($str,$this->key);
        $data = $this->ToArray($decrypt);
        return $data;
    }

    //加密
    private function encrypt($input, $key){
        $encrypted_openssl = openssl_encrypt($input, "AES-128-ECB", $key, OPENSSL_RAW_DATA);
        $data = bin2hex($encrypted_openssl);
        return $data;
    }
    //解密
    private function decrypt($input, $key){
        $encrypted_openssl = openssl_decrypt($input, "AES-128-ECB", $key, OPENSSL_RAW_DATA);
        $data = bin2hex($encrypted_openssl);
        return $data;
    }
    //128位不满时填充0
    private function zeroPadding($stringHex){
        $len=strlen($stringHex);
        if ($len<32){
            for($i = $len; $i < 32; $i++){
                $stringHex .= '0';
            }
        }
        return $stringHex;
    }
    //解析16进制字符串
    private function hexChr($stringHex){
        $str = '';
        for ($i = 0; $i < strlen($stringHex); $i += 2) {
            $str .= chr(hexdec(substr($stringHex, $i, 2)));
        }
        return $str;
    }
    //将秘钥转为16进制
    private function stringToHex($strKey){
        $key='';
        for ($i=0;$i<strlen($strKey);$i++){
            $key .= bin2hex(substr($strKey, $i, 1));
        }
        return $key;
    }
    //转成数组
    private function ToArray($data){
        $array = array();
        for ($i = 0; $i < strlen($data); $i += 2) {
            $array[]='0x'.substr($data, $i, 2);
        }
        return $array;
    }


}