Completed
Push — master ( d732f2...827150 )
by smiley
01:50
created

BoxKeypair::create()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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