对称加密算法:AES,可逆(DES的替代者)
话不多说。直接上代码
<?php
namespace app\common;
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 还不是很清楚
* 使用意见。后台请使用 AES-128-ECB API传输加密建议使用 AES-128-CBC 并携带IV向量。必备
*
*/
public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
{
// key是必须要设置的
$this->secret_key = isset($key) ? $key : '132465';
$this->method = $method;
$this->iv = $iv;
$this->options = $options;
}
/**
* 加密方法,对数据进行加密,返回加密后的数据
*
* @param string $data 要加密的数据
*
* @return string
*
*/
public function encrypt($data)
{
$aesValue = openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
return urlsafe_b64encode($aesValue);
}
/**
* 解密方法,对数据进行解密,返回解密后的数据
*
* @param string $data 要解密的数据
*
* @return string
*
*/
public function decrypt($data)
{
$data = urlsafe_b64decode($data);
return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
}
urlsafe_b64decode 和 urlsafe_b64encode实现如下
function urlsafe_b64encode ($string) {
$data = base64_encode ($string);
$data = str_replace ( array('+', '/', '=') , array('-', '_', '') , $data );
return $data;
}
// URL安全的字符串解码:
function urlsafe_b64decode ($string) {
$data = str_replace ( array('-', '_') , array('+', '/') , $string );
$mod4 = strlen ($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
使用范例(Thinkphp6)
$aes = new OpenSSLAES($this->key);
//加密
$aesValue = $aes->encrypt('123465456465');
//解密
$value = $aes->decrypt($aesValue);