BoxKeypair::create()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 18
rs 9.6111
1
<?php
2
/**
3
 * Class BoxKeypair
4
 *
5
 * @filesource   BoxKeypair.php
6
 * @created      24.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 sodium_crypto_box_keypair, sodium_crypto_box_publickey, sodium_crypto_box_publickey_from_secretkey,
16
	sodium_crypto_box_secretkey, sodium_crypto_box_seed_keypair, sodium_memzero, strlen;
17
18
use const SODIUM_CRYPTO_BOX_SECRETKEYBYTES, SODIUM_CRYPTO_BOX_SEEDBYTES;
19
20
class BoxKeypair extends CryptoKeypairAbstract{
21
22
	/**
23
	 * @inheritdoc
24
	 *
25
	 * @throws \chillerlan\Cryptobox\CryptoException
26
	 */
27
	public function create(string $seed_bin = null):CryptoKeypairInterface{
28
29
		if($seed_bin !== null && strlen($seed_bin) !== SODIUM_CRYPTO_BOX_SEEDBYTES){
30
			throw new CryptoException('invalid seed length');
31
		}
32
33
		$this->keypair = $seed_bin
34
			? sodium_crypto_box_seed_keypair($seed_bin)
35
			: sodium_crypto_box_keypair();
36
37
		$this->secret = sodium_crypto_box_secretkey($this->keypair);
38
		$this->public = sodium_crypto_box_publickey($this->keypair);
39
40
		if($seed_bin !== null){
41
			sodium_memzero($seed_bin);
42
		}
43
44
		return $this;
45
	}
46
47
	/**
48
	 * @param string $secret_bin
49
	 *
50
	 * @return \chillerlan\Cryptobox\CryptoKeypairInterface
51
	 * @throws \chillerlan\Cryptobox\CryptoException
52
	 */
53
	public function createFromSecret(string $secret_bin):CryptoKeypairInterface{
54
55
		if(strlen($secret_bin) !== SODIUM_CRYPTO_BOX_SECRETKEYBYTES){
56
			throw new CryptoException('invalid secret key length');
57
		}
58
59
		$this->secret  = $secret_bin;
60
		$this->public  = sodium_crypto_box_publickey_from_secretkey($this->secret);
61
		$this->keypair = $this->secret.$this->public;
62
63
		sodium_memzero($secret_bin);
64
65
		return $this;
66
	}
67
68
}
69