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