Crypt   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 53
ccs 18
cts 18
cp 1
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A generateRandomBytes() 0 9 3
A encrypt() 0 12 1
A decrypt() 0 6 1
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