-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
AESGCM.php
67 lines (56 loc) · 1.77 KB
/
AESGCM.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
declare(strict_types=1);
namespace Jose\Component\Encryption\Algorithm\ContentEncryption;
use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithm;
use const OPENSSL_RAW_DATA;
use ParagonIE\ConstantTime\Base64UrlSafe;
use RuntimeException;
abstract class AESGCM implements ContentEncryptionAlgorithm
{
public function allowedKeyTypes(): array
{
return []; //Irrelevant
}
public function encryptContent(
string $data,
string $cek,
string $iv,
?string $aad,
string $encoded_protected_header,
?string &$tag = null
): string {
$calculated_aad = $encoded_protected_header;
if ($aad !== null) {
$calculated_aad .= '.' . Base64UrlSafe::encodeUnpadded($aad);
}
$tag = '';
$result = openssl_encrypt($data, $this->getMode(), $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad);
if ($result === false) {
throw new RuntimeException('Unable to encrypt the content');
}
return $result;
}
public function decryptContent(
string $data,
string $cek,
string $iv,
?string $aad,
string $encoded_protected_header,
string $tag
): string {
$calculated_aad = $encoded_protected_header;
if ($aad !== null) {
$calculated_aad .= '.' . Base64UrlSafe::encodeUnpadded($aad);
}
$result = openssl_decrypt($data, $this->getMode(), $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad);
if ($result === false) {
throw new RuntimeException('Unable to decrypt the content');
}
return $result;
}
public function getIVSize(): int
{
return 96;
}
abstract protected function getMode(): string;
}