AesEncrypter::decryptData()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 12
c 1
b 0
f 1
dl 0
loc 18
rs 9.8666
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace SprykerEco\Zed\Heidelpay\Business\Encrypter;
9
10
use SprykerEco\Zed\Heidelpay\HeidelpayConfig;
11
12
class AesEncrypter implements EncrypterInterface
13
{
14
    public const CYPHER_METHOD = 'aes-256-cbc';
15
    public const INIT_VECTOR_SEPARATOR = ':::';
16
17
    /**
18
     * @var \SprykerEco\Zed\Heidelpay\HeidelpayConfig
19
     */
20
    protected $config;
21
22
    /**
23
     * @param \SprykerEco\Zed\Heidelpay\HeidelpayConfig $config
24
     */
25
    public function __construct(HeidelpayConfig $config)
26
    {
27
        $this->config = $config;
28
    }
29
30
    /**
31
     * @param string $data
32
     *
33
     * @return string
34
     */
35
    public function encryptData(string $data): string
36
    {
37
        $encryptionKey = $this->config
38
            ->getEncryptionKey();
39
        $initVector = $this->getRandomPseudoBytes();
40
41
        $encryptedData = openssl_encrypt(
42
            $data,
43
            static::CYPHER_METHOD,
44
            $encryptionKey,
45
            OPENSSL_RAW_DATA,
46
            $initVector
47
        );
48
49
        return implode(static::INIT_VECTOR_SEPARATOR, [$encryptedData, base64_encode($initVector)]);
50
    }
51
52
    /**
53
     * @param string $data
54
     *
55
     * @return string|null
56
     */
57
    public function decryptData(string $data)
58
    {
59
        $encryptionKey = $this->config
60
            ->getEncryptionKey();
61
62
        $dataChunks = explode(static::INIT_VECTOR_SEPARATOR, $data);
63
        if (count($dataChunks) !== 2) {
64
            return null;
65
        }
66
67
        [$encryptedData, $initVector] = $dataChunks;
68
69
        return openssl_decrypt(
70
            $encryptedData,
71
            static::CYPHER_METHOD,
72
            $encryptionKey,
73
            OPENSSL_RAW_DATA,
74
            base64_decode($initVector)
75
        );
76
    }
77
78
    /**
79
     * @return string
80
     */
81
    protected function getRandomPseudoBytes(): string
82
    {
83
        $cipherIvLength = openssl_cipher_iv_length(static::CYPHER_METHOD);
84
85
        return openssl_random_pseudo_bytes($cipherIvLength);
86
    }
87
}
88