Commit | Line | Data |
---|---|---|
e9631169 S |
1 | <?php |
2 | /** | |
3 | * @author Jan Altensen (Stricted) | |
4 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> | |
dd76f288 | 5 | * @copyright 2015-2016 Jan Altensen (Stricted) |
e9631169 S |
6 | */ |
7 | trait CryptLib { | |
8 | /** | |
9 | * sends the encrypted request to router | |
10 | * | |
11 | * @param string $path | |
12 | * @param mixed $fields | |
13 | * @param string $cookie | |
14 | * @return array | |
15 | */ | |
e94573dd | 16 | private function sendEncryptedRequest ($path, $fields, $cookie = false) { |
e9631169 S |
17 | $count = count($fields); |
18 | $fields = $this->encrypt(http_build_query($fields)); | |
e94573dd | 19 | return $this->sendRequest($path, $fields, $cookie, $count); |
e9631169 S |
20 | } |
21 | ||
22 | /** | |
23 | * decrypt data from router | |
24 | * | |
25 | * @param string $data | |
26 | * @return array | |
27 | */ | |
28 | private function decrypt ($data) { | |
29 | $iv = hex2bin(substr($this->challenge, 16, 16)); | |
30 | $adata = hex2bin(substr($this->challenge, 32, 16)); | |
31 | $key = hex2bin($this->derivedk); | |
32 | $enc = hex2bin($data); | |
33 | ||
061f7b31 S |
34 | if (PHP_VERSION_ID >= 70100) { |
35 | $ciphertext = substr($enc, 0, -8); | |
36 | $tag = substr($enc, strlen($enc)-8); | |
37 | ||
38 | return openssl_decrypt($ciphertext, 'aes-128-ccm', $key, OPENSSL_RAW_DATA, $iv, $tag, $adata); | |
39 | } | |
40 | else { | |
41 | $factory = new CryptLib\Cipher\Factory(); | |
42 | $aes = $factory->getBlockCipher('rijndael-128'); | |
43 | $aes->setKey($key); | |
44 | $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]); | |
061f7b31 S |
45 | $mode->decrypt($enc); |
46 | ||
47 | return $mode->finish(); | |
48 | } | |
e9631169 S |
49 | } |
50 | ||
51 | /** | |
52 | * decrypt data for the router | |
53 | * | |
54 | * @param string $data | |
55 | * @return string | |
56 | */ | |
57 | private function encrypt ($data) { | |
58 | $iv = hex2bin(substr($this->challenge, 16, 16)); | |
59 | $adata = hex2bin(substr($this->challenge, 32, 16)); | |
60 | $key = hex2bin($this->derivedk); | |
61 | ||
061f7b31 S |
62 | if (empty($data)) { |
63 | return $data; | |
64 | } | |
e9631169 | 65 | |
061f7b31 S |
66 | if (PHP_VERSION_ID >= 70100) { |
67 | $tag = null; | |
68 | $encdata = openssl_encrypt($data, 'aes-128-ccm', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv, $tag, $adata, 8); | |
b0b2052a | 69 | |
061f7b31 S |
70 | return bin2hex($encdata . $tag); |
71 | } | |
72 | else { | |
73 | $factory = new CryptLib\Cipher\Factory(); | |
74 | $aes = $factory->getBlockCipher('rijndael-128'); | |
75 | $aes->setKey($key); | |
76 | $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]); | |
77 | $mode->encrypt($data); | |
b0b2052a | 78 | |
061f7b31 S |
79 | return bin2hex($mode->finish()); |
80 | } | |
e9631169 S |
81 | } |
82 | } |