1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\JWX\JWE\EncryptionAlgorithm; |
6
|
|
|
|
7
|
|
|
use Sop\GCM\AESGCM; |
8
|
|
|
use Sop\GCM\Exception\AuthenticationException as GCMAuthException; |
9
|
|
|
use Sop\JWX\JWE\ContentEncryptionAlgorithm; |
10
|
|
|
use Sop\JWX\JWE\Exception\AuthenticationException; |
11
|
|
|
use Sop\JWX\JWT\Parameter\EncryptionAlgorithmParameter; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Base class for algorithms implementing AES in Galois/Counter mode. |
15
|
|
|
* |
16
|
|
|
* @see https://tools.ietf.org/html/rfc7518#section-5.3 |
17
|
|
|
*/ |
18
|
|
|
abstract class AESGCMAlgorithm implements ContentEncryptionAlgorithm |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* {@inheritdoc} |
22
|
|
|
*/ |
23
|
15 |
|
public function encrypt(string $plaintext, string $key, string $iv, |
24
|
|
|
string $aad): array |
25
|
|
|
{ |
26
|
15 |
|
$this->_validateKey($key); |
27
|
14 |
|
$this->_validateIV($iv); |
28
|
13 |
|
return AESGCM::encrypt($plaintext, $aad, $key, $iv, 16); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
*/ |
34
|
5 |
|
public function decrypt(string $ciphertext, string $key, string $iv, |
35
|
|
|
string $aad, string $auth_tag): string |
36
|
|
|
{ |
37
|
5 |
|
$this->_validateKey($key); |
38
|
5 |
|
$this->_validateIV($iv); |
39
|
|
|
try { |
40
|
5 |
|
$plaintext = AESGCM::decrypt($ciphertext, $auth_tag, $aad, $key, $iv); |
41
|
1 |
|
} catch (GCMAuthException $e) { |
42
|
1 |
|
throw new AuthenticationException('Message authentication failed.'); |
43
|
|
|
} |
44
|
4 |
|
return $plaintext; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* {@inheritdoc} |
49
|
|
|
*/ |
50
|
19 |
|
public function ivSize(): int |
51
|
|
|
{ |
52
|
19 |
|
return 12; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* {@inheritdoc} |
57
|
|
|
*/ |
58
|
5 |
|
public function headerParameters(): array |
59
|
|
|
{ |
60
|
5 |
|
return [EncryptionAlgorithmParameter::fromAlgorithm($this)]; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Check that key is valid. |
65
|
|
|
* |
66
|
|
|
* @param string $key |
67
|
|
|
* |
68
|
|
|
* @throws \RuntimeException |
69
|
|
|
*/ |
70
|
19 |
|
final protected function _validateKey(string $key): void |
71
|
|
|
{ |
72
|
19 |
|
if (strlen($key) !== $this->keySize()) { |
73
|
1 |
|
throw new \RuntimeException('Invalid key size.'); |
74
|
|
|
} |
75
|
18 |
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Check that IV is valid. |
79
|
|
|
* |
80
|
|
|
* @param string $iv |
81
|
|
|
* |
82
|
|
|
* @throws \RuntimeException |
83
|
|
|
*/ |
84
|
18 |
|
final protected function _validateIV(string $iv): void |
85
|
|
|
{ |
86
|
18 |
|
if (strlen($iv) !== $this->ivSize()) { |
87
|
1 |
|
throw new \RuntimeException('Invalid IV length.'); |
88
|
|
|
} |
89
|
17 |
|
} |
90
|
|
|
} |
91
|
|
|
|