Encryption.php
2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/**
* AES, 128 ECB模式加密数据
*/
namespace WebPlugin;
class Encryption {
//密钥
private static $_secrect_key = 'yoho9646abcdefgh';
//前面补8位0
private static $_preString = '00000000';
/**
* 加密方法
* @param string $str
* @return string
*/
public static function encrypt($str){
$str = self::$_preString.$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);
$encrypt_str = ltrim($encrypt_str, self::$_preString);
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;
}
/**
* 移去填充算法
* @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;
}
}