**AES 加密解密,可用于接口數據提供給第三方使用。**
使用 `AES-128-ECB`方式。
~~~
aes_encode($data,$type='AES-128-ECB',$key='',$iv='')
aes_decode($data,$type='AES-128-ECB',$key='',$iv='')
~~~
**事例代碼**
1.加密
~~~
$key = "516610f18f";
$iv = "6fc5328948e9edd17d";
$title = "demo15";
$data = [
'title'=> $title,
'time' => time(),
];
$data = json_encode($data);
echo urlencode(aes_encode($data,$type='AES-128-ECB',$key,$iv));
~~~
2.url參數形式解密
~~~
$sign = $_GET['sign'];
$title = $_GET['title'];
if(!$sign){
exit('Params error');
}
//$res怎么來的,自己看著辦
$secret_key = $res['secret_key'];
$secret_id = $res['secret_id'];
$sign = urldecode($sign);
$arr = aes_decode($sign,'AES-128-ECB',$secret_id,$secret_key);
$arr = json_decode($arr,true);
if($arr['title']){
if($arr['time'] < time()-300){
exit('Access Deny');
}
//這里就解密成功了。可以添加自己的邏輯。
}
exit('Access Deny');
~~~
*****
《《《本系統不用看以下代碼》》》
*****
**以下在需要使用到的方法或類,本系統已內置**
~~~
/**
* AES加密
// aes 加密
$config['aes_key'] = "123456";
$config['aes_iv'] = md5('app_sun');
$token = urlencode(aes_encode($d));
*/
function aes_encode($data,$type='AES-128-ECB',$key='',$iv=''){
global $config;
if(!$key){
$key = $config['aes_key'];
}
if(!$iv){
$iv = $config['aes_iv'];
}
$obj = new \lib\Aes($key,$type,$key,$iv);
return base64_encode($obj->encrypt($data));
}
/**
* AES解密
$token = $_GET['token'];
$token = aes_decode($token);
pr($token);
*/
function aes_decode($data,$type='AES-128-ECB',$key='',$iv=''){
global $config;
if(!$key){
$key = $config['aes_key'];
}
if(!$iv){
$iv = $config['aes_iv'];
}
$data = base64_decode($data);
$obj = new \lib\Aes($key,$type,$key,$iv);
return $obj->decrypt($data);
}
~~~
類實現
~~~
<?php
namespace lib;
class Aes
{
/**
* var string $method 加解密方法,可通過openssl_get_cipher_methods()獲得
*/
protected $method;
/**
* var string $secret_key 加解密的密鑰
*/
protected $secret_key;
/**
* var string $iv 加解密的向量,有些方法需要設置比如CBC
*/
protected $iv;
/**
* var string $options (不知道怎么解釋,目前設置為0沒什么問題)
*/
protected $options;
/**
* 構造函數
*
* @param string $key 密鑰
* @param string $method 加密方式
* @param string $iv iv向量
* @param mixed $options 還不是很清楚
*
*/
public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
{
// key是必須要設置的
$this->secret_key = isset($key) ? $key : 'morefun';
$this->method = $method;
$this->iv = $iv;
$this->options = $options;
}
/**
* 加密方法,對數據進行加密,返回加密后的數據
*
* @param string $data 要加密的數據
*
* @return string
*
*/
public function encrypt($data)
{
return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
/**
* 解密方法,對數據進行解密,返回解密后的數據
*
* @param string $data 要解密的數據
*
* @return string
*
*/
public function decrypt($data)
{
return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
}
~~~