AESUtil.php
2.6 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
* Created by PhpStorm.
* User: ruidiudiu
* Date: 2018/11/12
* Time: 14:44
*/
namespace aesutil;
class AESUtil{
private $key='';//秘钥的十六进制标识
private $keyCrypt='';//加密后的16进制秘钥
/**
* @param string $_key 密钥
*/
public function __construct($_key = '1111111111111111'){
$hexKey = $this->stringToHex($_key);
$k = $this->hexChr($hexKey);
$this->key = $k;
$this->keyCrypt = $this->encrypt('',$k);
}
//进行指令加密
public function encryption($stringHex){
//填充0
$stringHex=$this->zeroPadding($stringHex);
//解析16进制字符
$str = $this->hexChr($stringHex);
//加密
$encrypt=$this->encrypt($str,$this->key);
//截取指令
$instruction=substr($encrypt,0,strpos($encrypt,$this->keyCrypt));
$data = $this->ToArray($instruction);
return $data;
}
//进行指令解密
public function decryption($stringHex){
$crypt = $stringHex.$this->keyCrypt;
$str = $this->hexChr($crypt);
$decrypt = $this->decrypt($str,$this->key);
$data = $this->ToArray($decrypt);
return $data;
}
//加密
private function encrypt($input, $key){
$encrypted_openssl = openssl_encrypt($input, "AES-128-ECB", $key, OPENSSL_RAW_DATA);
$data = bin2hex($encrypted_openssl);
return $data;
}
//解密
private function decrypt($input, $key){
$encrypted_openssl = openssl_decrypt($input, "AES-128-ECB", $key, OPENSSL_RAW_DATA);
$data = bin2hex($encrypted_openssl);
return $data;
}
//128位不满时填充0
private function zeroPadding($stringHex){
$len=strlen($stringHex);
if ($len<32){
for($i = $len; $i < 32; $i++){
$stringHex .= '0';
}
}
return $stringHex;
}
//解析16进制字符串
private function hexChr($stringHex){
$str = '';
for ($i = 0; $i < strlen($stringHex); $i += 2) {
$str .= chr(hexdec(substr($stringHex, $i, 2)));
}
return $str;
}
//将秘钥转为16进制
private function stringToHex($strKey){
$key='';
for ($i=0;$i<strlen($strKey);$i++){
$key .= bin2hex(substr($strKey, $i, 1));
}
return $key;
}
//转成数组
private function ToArray($data){
$array = array();
for ($i = 0; $i < strlen($data); $i += 2) {
$array[]='0x'.substr($data, $i, 2);
}
return $array;
}
}