Completed
Push — middleware-wip ( 8fd059...e9d8ee )
by Romain
03:01
created

HashService::encrypt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/*
3
 * 2017 Romain CANON <[email protected]>
4
 *
5
 * This file is part of the TYPO3 FormZ project.
6
 * It is free software; you can redistribute it and/or modify it
7
 * under the terms of the GNU General Public License, either
8
 * version 3 of the License, or any later version.
9
 *
10
 * For the full copyright and license information, see:
11
 * http://www.gnu.org/licenses/gpl-3.0.html
12
 */
13
14
namespace Romm\Formz\Service;
15
16
use Romm\Formz\Exceptions\ExtensionNotLoadedException;
17
use Romm\Formz\Service\Traits\SelfInstantiateTrait;
18
use TYPO3\CMS\Core\SingletonInterface;
19
20
class HashService implements SingletonInterface
21
{
22
    use SelfInstantiateTrait;
23
24
    /**
25
     * @var string
26
     */
27
    protected $sslCipher = 'AES-256-CBC'; //@todo
28
29
    /**
30
     * @var string
31
     */
32
    protected $sslPassword = 'password!'; //@todo
33
34
    /**
35
     * @param string $value
36
     * @return string
37
     */
38
    public function getHash($value)
39
    {
40
        return hash('sha256', $value);
41
    }
42
43
    /**
44
     * Encrypts data using OpenSSL library.
45
     *
46
     * @param mixed $data
47
     * @return string
48
     */
49
    public function encrypt($data)
50
    {
51
        $this->checkOpenSslAvailability();
52
53
        return openssl_encrypt(json_encode($data), $this->sslCipher, $this->sslPassword);
54
    }
55
56
    /**
57
     * Decrypts a hashed string using OpenSSL library.
58
     *
59
     * @param string $string
60
     * @return mixed
61
     */
62
    public function decrypt($string)
63
    {
64
        $this->checkOpenSslAvailability();
65
66
        $data = openssl_decrypt($string, $this->sslCipher, $this->sslPassword);
67
68
        return $data === false
69
            ? false
70
            : json_decode($data, true);
71
    }
72
73
    /**
74
     * Checks that the `openssl` PHP extension is loaded.
75
     *
76
     * @throws ExtensionNotLoadedException
77
     */
78
    protected function checkOpenSslAvailability()
79
    {
80
        if (false === extension_loaded('openssl')) {
81
            throw ExtensionNotLoadedException::openSslNotLoaded();
82
        }
83
    }
84
}
85