<?php

/**
 * @Author: 思睿软件
 * @Date:   2019-12-31 10:39:19
 * @Last Modified by:   xjx
 * @Last Modified time: 2019-12-31 10:58:22
 * 加密 解密类
 * js互通
 * key 存放于数据库配置  安装使用
 */

namespace util;

use think\facade\Config;

class McryptECB{

	static function getcode(){
		return Config::get('secret_key') ? Config::get('secret_key'):'siruisoft';
	}
    
	/**
	 * [encrypt description]
	 * @Author   思睿软件<363359328@qq.com>
	 * @DateTime 2019-12-31T10:46:51+0800
	 * @param    [type]                   $string [description]
	 * @return   [type]                   $string [description]
	 * 加密
	 */
	static function encrypt($string){
		if(empty($string)) return '';
	    $code = md5(self::getcode());
	    $iv = substr($code,0,16);
	    $key = substr($code,16);
	    try{
	    	return str_replace(['+', '/'], ['-', '_'],base64_encode(openssl_encrypt($string,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv)));
	    }catch(Exception $e){
	    	exit('加密错误,需要开启openssl扩展');
	    }
	    
	}


	static  function decrypt($string){
		if(empty($string)) return '';
	    $code = md5(self::getcode());
	    $iv = substr($code,0,16);
	    $key = substr($code,16);
	    try{
	    	$string = str_replace(['-', '_'],['+', '/'],$string);
	    	return openssl_decrypt(base64_decode($string),"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv);
	    }catch(Exception $e){
	    	exit('解密错误,需要开启openssl扩展');
	    }
	}
}
