Passed
Pull Request — master (#190)
by Arman
02:47
created

SymmetricEncryptionAdapter::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 9
rs 10
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.5
13
 */
14
15
namespace Quantum\Libraries\Encryption\Adapters;
16
17
use Quantum\Libraries\Encryption\Contracts\EncryptionInterface;
18
use Quantum\Libraries\Encryption\Exceptions\CryptorException;
19
use Quantum\App\Exceptions\AppException;
20
use Quantum\Exceptions\BaseException;
21
22
/**
23
 * Class SymmetricEncryptionAdapter
24
 * @package Quantum\Libraries\Encryption
25
 */
26
class SymmetricEncryptionAdapter implements EncryptionInterface
27
{
28
29
    /**
30
     * Cipher method
31
     */
32
    const CIPHER_METHOD = 'aes-256-cbc';
33
34
    /**
35
     * @var string
36
     */
37
    private $appKey;
38
39
    /**
40
     * @throws BaseException
41
     */
42
    public function __construct()
43
    {
44
        $appKey = config()->get('app_key');
45
46
        if (!$appKey) {
47
            throw AppException::missingAppKey();
48
        }
49
50
        $this->appKey = $appKey;
51
    }
52
53
    /**
54
     * @param string $plain
55
     * @return string
56
     */
57
    public function encrypt(string $plain): string
58
    {
59
        $iv = $this->generateIV();
60
61
        $encrypted = openssl_encrypt($plain, self::CIPHER_METHOD, $this->appKey, 0, $iv);
62
63
        return base64_encode(base64_encode($encrypted) . '::' . base64_encode($iv));
64
    }
65
66
    /**
67
     * @param string $encrypted
68
     * @return string
69
     * @throws CryptorException
70
     */
71
    public function decrypt(string $encrypted): string
72
    {
73
        if (!valid_base64($encrypted)) {
74
            return $encrypted;
75
        }
76
77
        $data = explode('::', base64_decode($encrypted), 2);
78
79
        if (empty($data) || count($data) < 2) {
80
            throw CryptorException::invalidCipher();
81
        }
82
83
        $encryptedData = base64_decode($data[0]);
84
        $iv = base64_decode($data[1]);
85
86
        return openssl_decrypt($encryptedData, self::CIPHER_METHOD, $this->appKey, 0, $iv);
87
    }
88
89
    /**
90
     * @return string
91
     */
92
    private function generateIV(): string
93
    {
94
        $length = openssl_cipher_iv_length(self::CIPHER_METHOD);
95
        return openssl_random_pseudo_bytes($length);
96
    }
97
}