|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is part of the Zest Framework. |
| 5 | + * |
| 6 | + * @author Malik Umer Farooq <lablnet01@gmail.com> |
| 7 | + * @author-profile https://www.facebook.com/malikumerfarooq01/ |
| 8 | + * |
| 9 | + * For the full copyright and license information, please view the LICENSE |
| 10 | + * file that was distributed with this source code. |
| 11 | + * |
| 12 | + * @since 3.0.0 |
| 13 | + * |
| 14 | + * @license MIT |
| 15 | + */ |
| 16 | + |
| 17 | +namespace Lablnet\Adapter; |
| 18 | + |
| 19 | +class SodiumEncryption extends AbstractAdapter |
| 20 | +{ |
| 21 | + /** |
| 22 | + * __Construct. |
| 23 | + * |
| 24 | + * @since 3.0.0 |
| 25 | + */ |
| 26 | + public function __construct($key = null) |
| 27 | + { |
| 28 | + if (!function_exists('sodium_crypto_secretbox_keygen')) { |
| 29 | + throw new \Exception('The sodium php extension does not installed or enabled', 500); |
| 30 | + } |
| 31 | + |
| 32 | + $this->key = sodium_crypto_secretbox_keygen(); |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Encrypt the message. |
| 37 | + * |
| 38 | + * @param (mixed) $data data to be encrypted |
| 39 | + * |
| 40 | + * @since 3.0.0 |
| 41 | + * |
| 42 | + * @return mixed |
| 43 | + */ |
| 44 | + public function encrypt($data) |
| 45 | + { |
| 46 | + $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); |
| 47 | + $token = base64_encode($nonce.sodium_crypto_secretbox($data, $nonce, $this->key).'&&'.$this->key); |
| 48 | + |
| 49 | + return $token; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Decrypt the message. |
| 54 | + * |
| 55 | + * @param (mixed) $token encrypted token |
| 56 | + * |
| 57 | + * @since 3.0.0 |
| 58 | + * |
| 59 | + * @return mixed |
| 60 | + */ |
| 61 | + public function decrypt($token) |
| 62 | + { |
| 63 | + $decoded = base64_decode($token); |
| 64 | + list($decoded, $this->key) = explode('&&', $decoded); |
| 65 | + if ($decoded === false) { |
| 66 | + throw new Exception('The decoding failed'); |
| 67 | + } |
| 68 | + if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) { |
| 69 | + throw new \Exception('The token was truncated'); |
| 70 | + } |
| 71 | + $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit'); |
| 72 | + $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); |
| 73 | + |
| 74 | + $plain = sodium_crypto_secretbox_open($ciphertext, |
| 75 | + $nonce, $this->key); |
| 76 | + |
| 77 | + if ($plain === false) { |
| 78 | + throw new \Exception('The message was tampered with in transit'); |
| 79 | + } |
| 80 | + |
| 81 | + return $plain; |
| 82 | + } |
| 83 | +} |
0 commit comments