| 1 | <?php |
| 2 | /** |
| 3 | * @author Jan Altensen (Stricted) |
| 4 | * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> |
| 5 | * @copyright 2015 Jan Altensen (Stricted) |
| 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 | */ |
| 16 | private function sentEncryptedRequest ($path, $fields, $cookie = false) { |
| 17 | $count = count($fields); |
| 18 | $fields = $this->encrypt(http_build_query($fields)); |
| 19 | return $this->sentRequest($path, $fields, $cookie, $count); |
| 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 | |
| 34 | $factory = new CryptLib\Cipher\Factory(); |
| 35 | $aes = $factory->getBlockCipher('rijndael-128'); |
| 36 | $aes->setKey($key); |
| 37 | $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]); |
| 38 | |
| 39 | $mode->decrypt($enc); |
| 40 | |
| 41 | return $mode->finish(); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * decrypt data for the router |
| 46 | * |
| 47 | * @param string $data |
| 48 | * @return string |
| 49 | */ |
| 50 | private function encrypt ($data) { |
| 51 | $iv = hex2bin(substr($this->challenge, 16, 16)); |
| 52 | $adata = hex2bin(substr($this->challenge, 32, 16)); |
| 53 | $key = hex2bin($this->derivedk); |
| 54 | |
| 55 | $factory = new CryptLib\Cipher\Factory(); |
| 56 | $aes = $factory->getBlockCipher('rijndael-128'); |
| 57 | $aes->setKey($key); |
| 58 | $mode = $factory->getMode('ccm', $aes, $iv, [ 'adata' => $adata, 'lSize' => 7]); |
| 59 | $mode->encrypt($data); |
| 60 | |
| 61 | return bin2hex($mode->finish()); |
| 62 | } |
| 63 | } |