Passed
Push — master ( 883646...00eb2e )
by Charles
02:59
created

Request::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace ncryptf;
4
5
use InvalidArgumentException;
6
use SodiumException;
7
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;
0 ignored issues
show
introduced by
The private property $nonce is not used, and could be removed.
Loading history...
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)
74
    {
75
        try {
76
            return \sodium_crypto_sign_detached(
77
                $request,
78
                $secretKey
79
            );
80
        } catch (SodiumException $e) {
81
            throw new InvalidArgumentException($e->getMessage());
82
        }
83
    }
84
}