Completed
Push — master ( c06d7d...864e1b )
by Charles
02:18
created

EncryptionKey::getBoxPublicKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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