-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmipacket.class.php
195 lines (143 loc) · 4.96 KB
/
mipacket.class.php
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<?php
/*
* Класс для работы с сетевыми udp-пакетами по протоколу miIO.
*
* + генерация ключа и вектора инициализации из токена
* + расшифровка
* + шифрование
* + парсинг udp-пакета
* + сборка udp-пакета
*
* https://github.com/OpenMiHome/mihome-binary-protocol
*
* Copyright (C) 2017 Agaphonov Dmitri aka skysilver [mailto:skysilver.da@gmail.com]
*/
class miPacket {
private $magic = '2131';
private $length = '';
private $unknown1 = '00000000';
private $devicetype = '';
private $serial = '';
public $ts = '';
private $checksum = '';
public $timediff = 0;
public $data = '';
public $info = array('devicetype' => '',
'serial' => '',
'token' => '');
private $token = '';
private $key = '';
private $iv = '';
private $firstSet = true;
/*
Сохранение токена.
*/
public function setToken($token) {
if ($this->verifyToken($token)) {
$this->token = $token;
$this->getKeyIv();
return true;
} else {
return false;
};
}
/*
Вывод токена.
*/
public function getToken() {
return $this->token;
}
/*
Проверка длины токена.
*/
private function verifyToken($token) {
if (strlen($token) == 32) return true;
else return false;
}
/*
Вычисление ключа шифрования и вектора первичной инициализации на основе токена.
*/
private function getKeyIv() {
$this->key = md5(hex2bin($this->token));
$this->iv = md5(hex2bin($this->key.$this->token));
}
/*
Шифрование данных.
*/
public function encryptData($data) {
if ($this->verifyToken($this->token)) {
return bin2hex(openssl_encrypt($data, 'AES-128-CBC', hex2bin($this->key), OPENSSL_RAW_DATA, hex2bin($this->iv)));
} else return false;
}
/*
Расшифровка данных.
*/
public function decryptData($data) {
if ($this->verifyToken($this->token)) {
return openssl_decrypt(hex2bin($data), 'AES-128-CBC', hex2bin($this->key), OPENSSL_RAW_DATA, hex2bin($this->iv));
} else return false;
}
/*
Формирование пакета.
*/
public function msgBuild($cmd) {
$this->data = $this->encryptData($cmd);
$this->length = sprintf('%04x', (int)strlen($this->data)/2 + 32);
//$this->ts = sprintf('%08x', hexdec($this->ts)); // продублировать локальное время устройства
//$this->ts = sprintf('%08x', (hexdec($this->ts) + 1)); // плюс 1 секунда к локальному времени устройства
//$this->ts = sprintf('%08x', time()); // текущее время сервера
$this->ts = sprintf('%08x', time() + $this->timediff); // с учетом разницы времени между устройством и сервером
$packet = $this->magic.$this->length.$this->unknown1.$this->devicetype.$this->serial.$this->ts.$this->token.$this->data;
$this->checksum = md5(hex2bin($packet));
$packet = $this->magic.$this->length.$this->unknown1.$this->devicetype.$this->serial.$this->ts.$this->checksum.$this->data;
return $packet;
}
/*
Разбор пакета по полям.
*/
public function msgParse($msg) {
$this->magic = substr($msg, 0, 4);
$this->length = substr($msg, 4, 4);
$this->unknown1 = substr($msg, 8, 8);
$this->devicetype = substr($msg, 16, 4);
$this->serial = substr($msg, 20, 4);
$this->ts = substr($msg, 24, 8);
$this->checksum = substr($msg, 32, 32);
if ( ($this->length == '0020') && (strlen($msg)/2 == 32) ) {
$this->setToken(substr($msg, 32, 32));
// запомним разницу времени между устройством и сервером
$timediff = hexdec($this->ts) - time();
if ($this->firstSet && $timediff != 0) {
$this->timediff = $timediff;
}
if ($this->firstSet) $this->firstSet = false;
} else {
$data_length = strlen($msg) - 64;
if ($data_length > 0) {
$this->data = substr($msg, 64, $data_length);
}
}
$this->info['devicetype'] = $this->devicetype;
$this->info['serial'] = $this->serial;
$this->info['token'] = $this->token;
}
/*
Вывод заголовка пакета.
*/
public function printHead() {
echo 'magic: ' . $this->magic . PHP_EOL;
echo 'length: ' . $this->length . ' --> ' . hexdec($this->length) . ' байт' . PHP_EOL;
echo 'unknown1: ' . $this->unknown1 . PHP_EOL;
echo 'devicetype: ' . $this->devicetype . PHP_EOL;
echo 'serial: ' . $this->serial . PHP_EOL;
echo 'ts: ' . $this->ts . ' --> ' . hexdec($this->ts) . ' секунд' . ' --> ' . date('Y-m-d H:i:s', hexdec($this->ts)) . PHP_EOL;
echo 'checksum: ' . $this->checksum . PHP_EOL;
}
/*
Вывод полей пакета и данных.
*/
public function printPacket() {
$this->printHead();
echo 'data: ' . $this->data . PHP_EOL;
}
}