| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Jose\Component\Encryption\Algorithm\KeyEncryption; |
| 6 |
|
| 7 |
use InvalidArgumentException; |
| 8 |
use Jose\Component\Core\JWK; |
| 9 |
use Jose\Component\Core\Util\RSAKey; |
| 10 |
use Jose\Component\Encryption\Algorithm\KeyEncryption\Util\RSACrypt; |
| 11 |
use function in_array; |
| 12 |
|
| 13 |
abstract class RSA implements KeyEncryption |
| 14 |
{ |
| 15 |
public function allowedKeyTypes(): array |
| 16 |
{ |
| 17 |
return ['RSA']; |
| 18 |
} |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
public function encryptKey(JWK $key, string $cek, array $completeHeader, array &$additionalHeader): string |
| 25 |
{ |
| 26 |
$this->checkKey($key); |
| 27 |
$pub = RSAKey::toPublic(RSAKey::createFromJWK($key)); |
| 28 |
|
| 29 |
return RSACrypt::encrypt($pub, $cek, $this->getEncryptionMode(), $this->getHashAlgorithm()); |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
public function decryptKey(JWK $key, string $encrypted_cek, array $header): string |
| 36 |
{ |
| 37 |
$this->checkKey($key); |
| 38 |
if (! $key->has('d')) { |
| 39 |
throw new InvalidArgumentException('The key is not a private key'); |
| 40 |
} |
| 41 |
$priv = RSAKey::createFromJWK($key); |
| 42 |
|
| 43 |
return RSACrypt::decrypt($priv, $encrypted_cek, $this->getEncryptionMode(), $this->getHashAlgorithm()); |
| 44 |
} |
| 45 |
|
| 46 |
public function getKeyManagementMode(): string |
| 47 |
{ |
| 48 |
return self::MODE_ENCRYPT; |
| 49 |
} |
| 50 |
|
| 51 |
protected function checkKey(JWK $key): void |
| 52 |
{ |
| 53 |
if (! in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { |
| 54 |
throw new InvalidArgumentException('Wrong key type.'); |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
abstract protected function getEncryptionMode(): int; |
| 59 |
|
| 60 |
abstract protected function getHashAlgorithm(): ?string; |
| 61 |
} |