Passed
Push — master ( 24ce06...2e741c )
by Charles
03:15
created

Request   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 83
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A sign() 0 9 2
A getNonce() 0 3 1
A encrypt() 0 12 2
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;
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
        $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)
72
    {
73
        try {
74
            return \sodium_crypto_sign_detached(
75
                $request,
76
                $secretKey
77
            );
78
        } catch (SodiumException $e) {
79
            throw new InvalidArgumentException($e->getMessage());
80
        }
81
    }
82
83
    /**
84
     * Returns the nonce used
85
     *
86
     * @return string
87
     */
88
    public function getNonce()
89
    {
90
        return $this->nonce;
91
    }
92
}