Completed
Push — master ( 8ea8de...59eb2e )
by Charles
01:52
created

EncryptionKey::getBoxPublicKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace yrc\models\redis;
4
5
use yrc\redis\ActiveRecord;
6
use Yii;
7
8
final class EncryptionKey extends ActiveRecord
9
{
10
    /**
11
     * This is our default token lifespan
12
     * @const TOKEN_EXPIRATION_TIME
13
     */
14
    const OBJECT_EXPIRATION_TIME = '+15 minutes';
15
16
    /**
17
     * Model attributes
18
     * @return array
19
     */
20
    public function attributes()
21
    {
22
        return [
23
            'id',
24
            'secret',
25
            'expires_at',
26
            'hash'
27
        ];
28
    }
29
30
    /**
31
     * @return sodium_crypto_box_publickey
32
     */
33
    public function getBoxPublicKey()
34
    {
35
        return sodium_crypto_box_publickey($this->getBoxKeyPair());
36
    }
37
38
    /**
39
     * @return sodium_crypto_box_keypair
40
     */
41
    public function getBoxKeyPair()
42
    {
43
        $secret = \base64_decode($this->secret);
44
        $public = sodium_crypto_box_publickey_from_secretkey($secret);
45
        return sodium_crypto_box_keypair_from_secretkey_and_publickey($secret, $public);
46
    }
47
48
    /**
49
     * Helper method to return an encryption key
50
     * @return EncryptionKey
51
     */
52
    public static function generate()
53
    {
54
        $boxKp = sodium_crypto_box_keypair();
55
        $obj = new static;
56
        $obj->secret = \base64_encode(sodium_crypto_box_secretkey($boxKp));
57
        $obj->hash = \hash('sha256', uniqid('__EncryptionKeyPairHash', true));
58
        $obj->expires_at = \strtotime(static::OBJECT_EXPIRATION_TIME);
59
60
        if ($obj->save()) {
61
            return $obj;
62
        }
63
64
        throw new \yii\base\Exception(Yii::t('yrc', 'Failed to generate security tokens'));
65
    }
66
}