ItemDecorator::encrypt()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 2
b 0
f 1
cc 1
eloc 8
nc 1
nop 1
crap 1
1
<?php
2
namespace Jsq\CacheEncryption\Password;
3
4
use Jsq\CacheEncryption\ItemDecorator as BaseItemDecorator;
5
use Psr\Cache\CacheItemInterface;
6
7
class ItemDecorator extends BaseItemDecorator
8
{
9
    /** @var string */
10
    private $password;
11
12 183
    public function __construct(
13
        CacheItemInterface $decorated,
14
        $password,
15
        $cipher
16
    ) {
17 183
        parent::__construct($cipher, $decorated);
18 183
        $this->password = $password;
19 183
    }
20
21 129
    protected function isDecryptable()
22
    {
23 129
        $data = $this->getDecorated()->get();
24
25 129
        return $data instanceof EncryptedValue
26 93
            && $data->getMac() === $this->authenticate(
27 93
                $this->getKey(),
28 129
                $data->getCipherText()
29
            );
30
    }
31
32 129
    protected function encrypt($data)
33
    {
34 129
        $iv = $this->generateIv();
35 129
        $encrypted = $this->encryptString(serialize($data), $this->password, $iv);
36
37 129
        return new EncryptedValue(
38
            $encrypted,
39 129
            $this->getCipherMethod(),
40
            $iv,
41 129
            $this->authenticate($this->getKey(), $encrypted)
42
        );
43
    }
44
45 66 View Code Duplication
    protected function decrypt($data)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
46
    {
47 66
        if (!$data instanceof EncryptedValue) return null;
48
49 66
        return unserialize($this->decryptString(
50 66
            $data->getCipherText(),
51 66
            $data->getMethod(),
52 66
            $this->password,
53 66
            $data->getInitializationVector()
54
        ));
55
    }
56
57 129
    private function authenticate($key, $cipherText)
58
    {
59 129
        return $this->hmac($cipherText, $this->hmac($key, $this->password));
60
    }
61
62 129
    private function hmac($data, $key) 
63
    {
64 129
        return hash_hmac('sha256', $data, $key);
65
    }
66
}
67