Box::create()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 10
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 16
rs 9.9332
1
<?php
2
/**
3
 * Class Box
4
 *
5
 * @filesource   Box.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_box, sodium_crypto_box_keypair_from_secretkey_and_publickey,
16
	sodium_crypto_box_open, sodium_memzero;
17
18
use const SODIUM_CRYPTO_BOX_NONCEBYTES, SODIUM_CRYPTO_BOX_PUBLICKEYBYTES, SODIUM_CRYPTO_BOX_SECRETKEYBYTES;
19
20
class Box extends CryptoBoxAbstract{
21
22
	/**
23
	 * @param string      $message
24
	 * @param string|null $nonce_bin
25
	 *
26
	 * @return \chillerlan\Cryptobox\CryptoBoxInterface
27
	 */
28
	public function create(string $message, string $nonce_bin = null):CryptoBoxInterface{
29
		$this->checkKeypair(SODIUM_CRYPTO_BOX_SECRETKEYBYTES, SODIUM_CRYPTO_BOX_PUBLICKEYBYTES);
30
31
		$message     = $this->checkMessage($message);
32
		$keypair     = sodium_crypto_box_keypair_from_secretkey_and_publickey($this->keypair->secret, $this->keypair->public);
33
		$this->nonce = $nonce_bin ?? random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);
34
		$this->box   = sodium_crypto_box($message, $this->nonce, $keypair);
35
36
		sodium_memzero($keypair);
37
		sodium_memzero($message);
38
39
		if($nonce_bin !== null){
40
			sodium_memzero($nonce_bin);
41
		}
42
43
		return $this;
44
	}
45
46
	/**
47
	 * @param string $box_bin
48
	 * @param string $nonce_bin
49
	 *
50
	 * @return \chillerlan\Cryptobox\CryptoBoxInterface
51
	 * @throws \chillerlan\Cryptobox\CryptoException
52
	 */
53
	public function open(string $box_bin, string $nonce_bin):CryptoBoxInterface{
54
		$this->checkKeypair(SODIUM_CRYPTO_BOX_SECRETKEYBYTES, SODIUM_CRYPTO_BOX_PUBLICKEYBYTES);
55
56
		$keypair       = sodium_crypto_box_keypair_from_secretkey_and_publickey($this->keypair->secret, $this->keypair->public);
57
		$this->message = sodium_crypto_box_open($box_bin, $nonce_bin, $keypair);
58
59
		sodium_memzero($keypair);
60
		sodium_memzero($box_bin);
61
		sodium_memzero($nonce_bin);
62
63
		if($this->message !== false){
64
			return $this;
65
		}
66
67
		throw new CryptoException('invalid box'); // @codeCoverageIgnore
68
	}
69
70
}
71