|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Nastoletni\Code\Infrastructure; |
|
6
|
|
|
|
|
7
|
|
|
use Nastoletni\Code\Application\Crypter\CrypterException; |
|
8
|
|
|
use Nastoletni\Code\Application\Crypter\PasteCrypter; |
|
9
|
|
|
use Nastoletni\Code\Domain\Paste; |
|
10
|
|
|
|
|
11
|
|
|
class AES256Crypter implements PasteCrypter |
|
12
|
|
|
{ |
|
13
|
|
|
private const CIPHER = 'aes-256-cbc'; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* {@inheritdoc} |
|
17
|
|
|
*/ |
|
18
|
2 |
|
public function encrypt(Paste &$paste, string $key): void |
|
19
|
|
|
{ |
|
20
|
2 |
|
$key = $this->keyToEncryptionKey($key); |
|
21
|
|
|
|
|
22
|
2 |
|
foreach ($paste->getFiles() as $file) { |
|
23
|
2 |
|
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(static::CIPHER)); |
|
24
|
|
|
|
|
25
|
2 |
|
$encrypted = openssl_encrypt( |
|
26
|
2 |
|
$file->getContent(), |
|
27
|
2 |
|
static::CIPHER, |
|
28
|
2 |
|
$key, |
|
29
|
2 |
|
0, |
|
30
|
2 |
|
$iv |
|
31
|
|
|
); |
|
32
|
2 |
|
$iv = base64_encode($iv); |
|
33
|
|
|
|
|
34
|
2 |
|
if (false === $encrypted) { |
|
35
|
|
|
throw new CrypterException('[OpenSSL] '.openssl_error_string()); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
2 |
|
$file->setContent($encrypted.':'.$iv); |
|
39
|
|
|
} |
|
40
|
2 |
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* {@inheritdoc} |
|
44
|
|
|
*/ |
|
45
|
2 |
|
public function decrypt(Paste &$paste, string $key): void |
|
46
|
|
|
{ |
|
47
|
2 |
|
$key = $this->keyToEncryptionKey($key); |
|
48
|
|
|
|
|
49
|
2 |
|
foreach ($paste->getFiles() as $file) { |
|
50
|
2 |
|
[$encrypted, $iv] = explode(':', $file->getContent()); |
|
|
|
|
|
|
51
|
|
|
|
|
52
|
2 |
|
$iv = base64_decode($iv); |
|
53
|
2 |
|
$decrypted = openssl_decrypt( |
|
54
|
2 |
|
$encrypted, |
|
55
|
2 |
|
static::CIPHER, |
|
56
|
2 |
|
$key, |
|
57
|
2 |
|
0, |
|
58
|
2 |
|
$iv |
|
59
|
|
|
); |
|
60
|
|
|
|
|
61
|
2 |
|
if (false === $decrypted) { |
|
62
|
|
|
throw new CrypterException('[OpenSSL] '.openssl_error_string()); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
2 |
|
$file->setContent($decrypted); |
|
66
|
|
|
} |
|
67
|
2 |
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* Translates key that varies in length to 256bit (32 bytes) encryption key. |
|
71
|
|
|
* |
|
72
|
|
|
* @param string $key |
|
73
|
|
|
* |
|
74
|
|
|
* @return string |
|
75
|
|
|
*/ |
|
76
|
2 |
|
private function keyToEncryptionKey(string $key): string |
|
77
|
|
|
{ |
|
78
|
2 |
|
return mb_substr(sha1($key, true), 0, 32); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.