|
|
<?php
|
|
|
/**
|
|
|
* aes加密解密
|
|
|
* AES, 128 ECB模式加密数据
|
|
|
*/
|
|
|
|
|
|
namespace Plugin;
|
|
|
|
|
|
class Encryption {
|
|
|
public static $iv = null;
|
|
|
public static $key = 'yoho9646abcdef';
|
|
|
public static $mode = MCRYPT_MODE_ECB;//MCRYPT_MODE_ECB、MCRYPT_MODE_CFB、MCRYPT_MODE_OFB、MCRYPT_MODE_NOFB、MCRYPT_MODE_CBC
|
|
|
private static $cipher = MCRYPT_RIJNDAEL_128;//MCRYPT_RIJNDAEL_192、MCRYPT_RIJNDAEL_256
|
|
|
|
|
|
public static function encrypt($data) {
|
|
|
$data = base64_encode(mcrypt_encrypt( self::$cipher, self::$key, $data, self::$mode, self::$iv));
|
|
|
return $data;
|
|
|
//密钥
|
|
|
private static $_secrect_key = 'yoho9646abcdefgh';
|
|
|
|
|
|
/**
|
|
|
* 加密方法
|
|
|
* @param string $str
|
|
|
* @return string
|
|
|
*/
|
|
|
public static function encrypt($str){
|
|
|
//AES, 128 ECB模式加密数据
|
|
|
$screct_key = self::$_secrect_key;
|
|
|
$str = trim($str);
|
|
|
$str = self::addPKCS7Padding($str);
|
|
|
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND);
|
|
|
$encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_ECB, $iv);
|
|
|
return base64_encode($encrypt_str);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 解密方法
|
|
|
* @param string $str
|
|
|
* @return string
|
|
|
*/
|
|
|
public static function decrypt($str){
|
|
|
//AES, 128 ECB模式加密数据
|
|
|
$screct_key = self::$_secrect_key;
|
|
|
$str = base64_decode($str);
|
|
|
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB),MCRYPT_RAND);
|
|
|
$encrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_ECB, $iv);
|
|
|
$encrypt_str = trim($encrypt_str);
|
|
|
$encrypt_str = self::stripPKSC7Padding($encrypt_str);
|
|
|
return $encrypt_str;
|
|
|
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 填充算法
|
|
|
* @param string $source
|
|
|
* @return string
|
|
|
*/
|
|
|
private static function addPKCS7Padding($source){
|
|
|
$source = trim($source);
|
|
|
$block = mcrypt_get_block_size('rijndael-128', 'ecb');
|
|
|
$pad = $block - (strlen($source) % $block);
|
|
|
if ($pad <= $block) {
|
|
|
$char = chr($pad);
|
|
|
$source .= str_repeat($char, $pad);
|
|
|
}
|
|
|
return $source;
|
|
|
}
|
|
|
public static function decrypt($data) {
|
|
|
$data = mcrypt_decrypt( self::$cipher, self::$key, base64_decode($data), self::$mode, self::$iv);
|
|
|
return $data;
|
|
|
/**
|
|
|
* 移去填充算法
|
|
|
* @param string $source
|
|
|
* @return string
|
|
|
*/
|
|
|
private static function stripPKSC7Padding($source){
|
|
|
$source = trim($source);
|
|
|
$char = substr($source, -1);
|
|
|
$num = ord($char);
|
|
|
if($num==62)return $source;
|
|
|
$source = substr($source,0,-$num);
|
|
|
return $source;
|
|
|
}
|
|
|
} |
|
|
\ No newline at end of file |
...
|
...
|
|