Total Complexity | 7 |
Total Lines | 74 |
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) |
||
31 | { |
||
32 | try { |
||
33 | $this->keypair = \sodium_crypto_box_keypair_from_secretkey_and_publickey( |
||
34 | $secretKey, |
||
35 | $publicKey |
||
36 | ); |
||
37 | } catch (SodiumException $e) { |
||
38 | throw new InvalidArgumentException($e->getMessage()); |
||
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 | if ($nonce === null) { |
||
52 | $nonce = \random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); |
||
53 | } |
||
54 | |||
55 | try { |
||
56 | return \sodium_crypto_box( |
||
57 | $request, |
||
58 | $nonce, |
||
59 | $this->keypair |
||
60 | ); |
||
61 | } catch (SodiumException $e) { |
||
62 | throw new InvalidArgumentException($e->getMessage()); |
||
63 | } |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * Creates a detached signature for the keypair |
||
68 | * |
||
69 | * @param string $request |
||
70 | * @param string $secretKey |
||
71 | * @return string |
||
72 | */ |
||
73 | public function sign(string $request, string $secretKey) |
||
82 | } |
||
83 | } |
||
84 | } |