| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Jose\Component\Encryption\Algorithm\ContentEncryption; |
| 6 |
|
| 7 |
use Jose\Component\Core\Util\Base64UrlSafe; |
| 8 |
use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithm; |
| 9 |
use RuntimeException; |
| 10 |
use function extension_loaded; |
| 11 |
use const OPENSSL_RAW_DATA; |
| 12 |
|
| 13 |
abstract class AESGCM implements ContentEncryptionAlgorithm |
| 14 |
{ |
| 15 |
public function __construct() |
| 16 |
{ |
| 17 |
if (! extension_loaded('openssl')) { |
| 18 |
throw new RuntimeException('Please install the OpenSSL extension'); |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
public function allowedKeyTypes(): array |
| 23 |
{ |
| 24 |
return []; |
| 25 |
} |
| 26 |
|
| 27 |
public function encryptContent( |
| 28 |
string $data, |
| 29 |
string $cek, |
| 30 |
string $iv, |
| 31 |
?string $aad, |
| 32 |
string $encoded_protected_header, |
| 33 |
?string &$tag = null |
| 34 |
): string { |
| 35 |
$calculated_aad = $encoded_protected_header; |
| 36 |
if ($aad !== null) { |
| 37 |
$calculated_aad .= '.' . Base64UrlSafe::encodeUnpadded($aad); |
| 38 |
} |
| 39 |
$tag = ''; |
| 40 |
$result = openssl_encrypt($data, $this->getMode(), $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad); |
| 41 |
if ($result === false) { |
| 42 |
throw new RuntimeException('Unable to encrypt the content'); |
| 43 |
} |
| 44 |
|
| 45 |
return $result; |
| 46 |
} |
| 47 |
|
| 48 |
public function decryptContent( |
| 49 |
string $data, |
| 50 |
string $cek, |
| 51 |
string $iv, |
| 52 |
?string $aad, |
| 53 |
string $encoded_protected_header, |
| 54 |
string $tag |
| 55 |
): string { |
| 56 |
$calculated_aad = $encoded_protected_header; |
| 57 |
if ($aad !== null) { |
| 58 |
$calculated_aad .= '.' . Base64UrlSafe::encodeUnpadded($aad); |
| 59 |
} |
| 60 |
|
| 61 |
$result = openssl_decrypt($data, $this->getMode(), $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad); |
| 62 |
if ($result === false) { |
| 63 |
throw new RuntimeException('Unable to decrypt the content'); |
| 64 |
} |
| 65 |
|
| 66 |
return $result; |
| 67 |
} |
| 68 |
|
| 69 |
public function getIVSize(): int |
| 70 |
{ |
| 71 |
return 96; |
| 72 |
} |
| 73 |
|
| 74 |
abstract protected function getMode(): string; |
| 75 |
} |