add support for php >= 7.1 (mcrypt extension used by cryptlib is deprecated and AEAD...
[GitHub/Stricted/speedport-hybrid-php-api.git] / lib / trait / CryptLib.class.php
CommitLineData
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 */
7trait 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]);
45
46 $mode->decrypt($enc);
47
48 return $mode->finish();
49 }
e9631169
S
50 }
51
52 /**
53 * decrypt data for the router
54 *
55 * @param string $data
56 * @return string
57 */
58 private function encrypt ($data) {
59 $iv = hex2bin(substr($this->challenge, 16, 16));
60 $adata = hex2bin(substr($this->challenge, 32, 16));
61 $key = hex2bin($this->derivedk);
62
061f7b31
S
63 if (empty($data)) {
64 return $data;
65 }
e9631169 66
061f7b31
S
67 if (PHP_VERSION_ID >= 70100) {
68 $tag = null;
69 $encdata = openssl_encrypt($data, 'aes-128-ccm', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv, $tag, $adata, 8);
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);
78 var_dump(bin2hex($mode->finish()));
79 return bin2hex($mode->finish());
80 }
e9631169
S
81 }
82}