Encrypt::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 21
ccs 12
cts 12
cp 1
rs 9.9
cc 2
nc 2
nop 7
crap 2
1
<?php
2
3
4
namespace Yiranzai\Tools;
5
6
class Encrypt
7
{
8
    public $data;
9
    public $plainText;
10
    public $cipher;
11
    public $key;
12
    public $options;
13
    public $iv;
14
    public $tag;
15
    public $aad;
16
    public $tagLength;
17
    public $cipherText;
18
    protected $flag = 1;
19
20 9
    public function __construct(
21
        $data,
22
        $cipher,
23
        $key,
24
        $options = 0,
25
        $iv = null,
26
        $tag = null,
27
        $aad = ''
28
    ) {
29 9
        if (!in_array($cipher, openssl_get_cipher_methods(), true)) {
30 3
            throw new \RuntimeException('cipher: ' . $cipher . 'not support');
31
        }
32 6
        $this->data = $data;
33 6
        $this->cipher = $cipher;
34 6
        $this->key = $key;
35 6
        $this->options = $options;
36 6
        $ivLen = openssl_cipher_iv_length($cipher);
37 6
        $this->iv = $iv ?? openssl_random_pseudo_bytes($ivLen);
38 6
        $this->tag = $tag;
39 6
        $this->aad = $aad;
40 6
        $this->tagLength = mb_strlen($this->tag);
41 6
    }
42
43 6
    public function encrypt()
44
    {
45 6
        if ($this->flag) {
46 6
            $this->plainText = $this->data;
47
        }
48 6
        $this->cipherText = openssl_encrypt(
49 6
            $this->plainText,
50 6
            $this->cipher,
51 6
            $this->key,
52 6
            $this->options,
53 6
            $this->iv,
54 6
            $this->tag,
55 6
            $this->aad,
56 6
            $this->tagLength
57
        );
58 6
        $this->flag = 0;
59 6
        return $this;
60
    }
61
62 6
    public function decrypt()
63
    {
64 6
        if ($this->flag) {
65 3
            $this->cipherText = $this->data;
66
        }
67 6
        $this->plainText = openssl_decrypt(
68 6
            $this->cipherText,
69 6
            $this->cipher,
70 6
            $this->key,
71 6
            $this->options,
72 6
            $this->iv,
73 6
            $this->tag,
74 6
            $this->aad
75
        );
76 6
        $this->flag = 0;
77 6
        return $this;
78
    }
79
}
80