1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class SecretBox |
4
|
|
|
* |
5
|
|
|
* @filesource SecretBox.php |
6
|
|
|
* @created 25.01.2018 |
7
|
|
|
* @package chillerlan\Cryptobox |
8
|
|
|
* @author Smiley <[email protected]> |
9
|
|
|
* @copyright 2018 Smiley |
10
|
|
|
* @license MIT |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace chillerlan\Cryptobox; |
14
|
|
|
|
15
|
|
|
use function random_bytes, sodium_crypto_secretbox, sodium_crypto_secretbox_open, sodium_memzero; |
16
|
|
|
|
17
|
|
|
use const SODIUM_CRYPTO_BOX_NONCEBYTES, SODIUM_CRYPTO_BOX_SECRETKEYBYTES; |
18
|
|
|
|
19
|
|
|
class SecretBox extends CryptoBoxAbstract{ |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param string $message |
23
|
|
|
* @param string|null $nonce_bin |
24
|
|
|
* |
25
|
|
|
* @return \chillerlan\Cryptobox\CryptoBoxInterface |
26
|
|
|
*/ |
27
|
|
|
public function create(string $message, string $nonce_bin = null):CryptoBoxInterface{ |
28
|
|
|
$this->checkKeypair(SODIUM_CRYPTO_BOX_SECRETKEYBYTES); |
29
|
|
|
|
30
|
|
|
$message = $this->checkMessage($message); |
31
|
|
|
$this->nonce = $nonce_bin ?? random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); |
32
|
|
|
$this->box = sodium_crypto_secretbox($message, $this->nonce, $this->keypair->secret); |
33
|
|
|
|
34
|
|
|
sodium_memzero($message); |
35
|
|
|
|
36
|
|
|
if($nonce_bin !== null){ |
37
|
|
|
sodium_memzero($nonce_bin); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $box_bin |
45
|
|
|
* @param string $nonce_bin |
46
|
|
|
* |
47
|
|
|
* @return \chillerlan\Cryptobox\CryptoBoxInterface |
48
|
|
|
* @throws \chillerlan\Cryptobox\CryptoException |
49
|
|
|
*/ |
50
|
|
|
public function open(string $box_bin, string $nonce_bin):CryptoBoxInterface{ |
51
|
|
|
$this->checkKeypair(SODIUM_CRYPTO_BOX_SECRETKEYBYTES); |
52
|
|
|
|
53
|
|
|
$this->message = sodium_crypto_secretbox_open($box_bin, $nonce_bin, $this->keypair->secret); |
54
|
|
|
|
55
|
|
|
if($this->message !== false){ |
56
|
|
|
return $this; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
throw new CryptoException('invalid box'); // @codeCoverageIgnore |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
} |
63
|
|
|
|