1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* The MIT License (MIT) |
7
|
|
|
* |
8
|
|
|
* Copyright (c) 2014-2017 Spomky-Labs |
9
|
|
|
* |
10
|
|
|
* This software may be modified and distributed under the terms |
11
|
|
|
* of the MIT license. See the LICENSE file for details. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Jose\Component\Encryption\Algorithm\ContentEncryption; |
15
|
|
|
|
16
|
|
|
use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithm; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Class AESGCM. |
20
|
|
|
*/ |
21
|
|
|
abstract class AESGCM implements ContentEncryptionAlgorithm |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
|
|
public function allowedKeyTypes(): array |
27
|
|
|
{ |
28
|
|
|
return []; //Irrelevant |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* {@inheritdoc} |
33
|
|
|
*/ |
34
|
|
|
public function encryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, ?string &$tag): string |
35
|
|
|
{ |
36
|
|
|
$calculated_aad = $encoded_protected_header; |
37
|
|
|
if (null !== $aad) { |
38
|
|
|
$calculated_aad .= '.'.$aad; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$C = openssl_encrypt($data, $this->getMode(), $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad); |
42
|
|
|
if (false === $C) { |
43
|
|
|
throw new \InvalidArgumentException('Unable to encrypt the data.'); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $C; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
*/ |
52
|
|
|
public function decryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, string $tag): string |
53
|
|
|
{ |
54
|
|
|
$calculated_aad = $encoded_protected_header; |
55
|
|
|
if (null !== $aad) { |
56
|
|
|
$calculated_aad .= '.'.$aad; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$P = openssl_decrypt($data, $this->getMode(), $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad); |
60
|
|
|
if (false === $P) { |
61
|
|
|
throw new \InvalidArgumentException('Unable to decrypt or to verify the tag.'); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $P; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return int |
69
|
|
|
*/ |
70
|
|
|
public function getIVSize(): int |
71
|
|
|
{ |
72
|
|
|
return 96; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @return string |
77
|
|
|
*/ |
78
|
|
|
abstract protected function getMode(): string; |
79
|
|
|
} |
80
|
|
|
|