| Total Complexity | 7 |
| Total Lines | 83 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | <?php declare(strict_types=1); |
||
| 8 | class Request |
||
| 9 | { |
||
| 10 | /** |
||
| 11 | * Sodium CryptoBox Keypair |
||
| 12 | * |
||
| 13 | * @var string |
||
| 14 | */ |
||
| 15 | private $keypair; |
||
| 16 | |||
| 17 | /** |
||
| 18 | * 24 byte nonce |
||
| 19 | * |
||
| 20 | * @var string |
||
| 21 | */ |
||
| 22 | private $nonce; |
||
| 23 | |||
| 24 | /** |
||
| 25 | * Constructor |
||
| 26 | * |
||
| 27 | * @param string $secretKey The 32 byte secret key |
||
| 28 | * @param string $publicKey The 32 byte public key |
||
| 29 | */ |
||
| 30 | public function __construct(string $secretKey, string $publicKey) |
||
| 39 | } |
||
| 40 | } |
||
| 41 | |||
| 42 | /** |
||
| 43 | * Encrypts a request |
||
| 44 | * |
||
| 45 | * @param string $request The raw HTTP request as a string |
||
| 46 | * @param string $nonce Optional nonce. If not provided, a 24 byte nonce will be generated |
||
| 47 | * @return string |
||
| 48 | */ |
||
| 49 | public function encrypt(string $request, string $nonce = null) |
||
| 50 | { |
||
| 51 | $this->nonce = $nonce ?? \random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); |
||
| 52 | |||
| 53 | try { |
||
| 54 | return \sodium_crypto_box( |
||
| 55 | $request, |
||
| 56 | $this->nonce, |
||
| 57 | $this->keypair |
||
| 58 | ); |
||
| 59 | } catch (SodiumException $e) { |
||
| 60 | throw new InvalidArgumentException($e->getMessage()); |
||
| 61 | } |
||
| 62 | } |
||
| 63 | |||
| 64 | /** |
||
| 65 | * Creates a detached signature for the keypair |
||
| 66 | * |
||
| 67 | * @param string $request |
||
| 68 | * @param string $secretKey |
||
| 69 | * @return string |
||
| 70 | */ |
||
| 71 | public function sign(string $request, string $secretKey) |
||
| 80 | } |
||
| 81 | } |
||
| 82 | |||
| 83 | /** |
||
| 84 | * Returns the nonce used |
||
| 85 | * |
||
| 86 | * @return string |
||
| 87 | */ |
||
| 88 | public function getNonce() |
||
| 91 | } |
||
| 92 | } |