1 | <?php |
||
2 | |||
3 | namespace Da\Mailer\Security; |
||
4 | |||
5 | use Da\Mailer\Model\MailMessage; |
||
6 | use phpseclib3\Crypt\AES; |
||
7 | |||
8 | final class Cypher implements CypherInterface |
||
9 | { |
||
10 | /** |
||
11 | * @var AES strategy |
||
12 | */ |
||
13 | private $strategy; |
||
14 | /** |
||
15 | * @var string the key to encode/decode |
||
16 | */ |
||
17 | private $key; |
||
18 | /** |
||
19 | * Cipher constructor. |
||
20 | * |
||
21 | * @param $key |
||
22 | */ |
||
23 | public function __construct($key, $iv) |
||
24 | 2 | { |
|
25 | $this->key = $key; |
||
26 | 2 | $this->iv = $iv; |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
27 | // initialize cypher with strongest mode and with AES. Is an anti-pattern and should be passed through the |
||
28 | // constructor as an argument, but this way we ensure the library does have the strongest strategy by default. |
||
29 | 2 | $this->strategy = new AES('cbc'); |
|
30 | $this->strategy->setKeyLength(256); |
||
31 | 2 | } |
|
32 | 2 | ||
33 | /** |
||
34 | * {@inheritdoc} |
||
35 | */ |
||
36 | public function encodeMailMessage(MailMessage $mailMessage) |
||
37 | 2 | { |
|
38 | $jsonEncodedMailMessage = json_encode($mailMessage, JSON_NUMERIC_CHECK); |
||
39 | 2 | $this->strategy->setKey($this->key); |
|
40 | 2 | $this->strategy->setIV($this->iv); |
|
41 | return base64_encode($this->strategy->encrypt($jsonEncodedMailMessage)); |
||
42 | 2 | } |
|
43 | |||
44 | /** |
||
45 | * {@inheritdoc} |
||
46 | */ |
||
47 | public function decodeMailMessage($encodedMailMessage) |
||
48 | 2 | { |
|
49 | $this->strategy->setKey($this->key); |
||
50 | 2 | $decryptedMailMessage = $this->strategy->decrypt(base64_decode($encodedMailMessage, true)); |
|
51 | 2 | $jsonDecodedMailMessageAttributes = json_decode($decryptedMailMessage, true); |
|
52 | 2 | return new MailMessage($jsonDecodedMailMessageAttributes); |
|
53 | } |
||
54 | } |
||
55 |