Crypt::encrypt()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 12
ccs 9
cts 9
cp 1
crap 1
rs 9.9666
1
<?php
2
3
namespace Bone\Crypt;
4
5
class Crypt
6
{
7
    /** @var string $cipher */
8
    private $cipher = 'aes-128-gcm';
9
10
    /** @var int $options */
11
    private $options = 0;
12
13
    /**
14
     * @param int $length
15
     * @return string
16
     */
17 1
    private function generateRandomBytes(int $length): string
18
    {
19 1
        $strong = false;
20
21
        do {
22 1
            $bytes = \openssl_random_pseudo_bytes($length, $strong);
23 1
        } while ($strong === false || $bytes === false);
24
25 1
        return $bytes;
26
    }
27
28
    /**
29
     * @param string $plaintext
30
     * @return array
31
     */
32 1
    public function encrypt(string $plaintext): array
33
    {
34 1
        $key = $this->generateRandomBytes(16);
35 1
        $ivLength = \openssl_cipher_iv_length($this->cipher);
36 1
        $iv = $this->generateRandomBytes($ivLength);
37 1
        $cipherText = \openssl_encrypt($plaintext, $this->cipher, $key, $this->options, $iv,$tag);
38
39
        return [
40 1
            'key' => \bin2hex($key),
41 1
            'iv' => \bin2hex($iv),
42 1
            'tag' => \bin2hex($tag),
43 1
            'ciphertext' => $cipherText,
44
        ];
45
    }
46
47
    /**
48
     * @param string $json
49
     * @param string $key
50
     * @return string
51
     */
52 1
    public function decrypt(string $json, string$key): string
53
    {
54 1
        $data = \json_decode($json);
55 1
        $result = \openssl_decrypt($data->ciphertext, $this->cipher, \hex2bin($key), $this->options, \hex2bin($data->iv), \hex2bin($data->tag));
56
57 1
        return $result;
58
    }
59
}
60