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) |
|
|
|
|
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
|
|
|
|
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.