| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Cose\Algorithm\Signature\RSA; |
| 6 |
|
| 7 |
use Cose\Algorithm\Signature\Signature; |
| 8 |
use Cose\Key\Key; |
| 9 |
use Cose\Key\RsaKey; |
| 10 |
use InvalidArgumentException; |
| 11 |
use function openssl_sign; |
| 12 |
use function openssl_verify; |
| 13 |
use Throwable; |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
abstract class RSA implements Signature |
| 19 |
{ |
| 20 |
public function sign(string $data, Key $key): string |
| 21 |
{ |
| 22 |
$key = $this->handleKey($key); |
| 23 |
if (! $key->isPrivate()) { |
| 24 |
throw new InvalidArgumentException('The key is not private.'); |
| 25 |
} |
| 26 |
|
| 27 |
try { |
| 28 |
openssl_sign($data, $signature, $key->asPem(), $this->getHashAlgorithm()); |
| 29 |
} catch (Throwable $e) { |
| 30 |
throw new InvalidArgumentException('Unable to sign the data', 0, $e); |
| 31 |
} |
| 32 |
|
| 33 |
return $signature; |
| 34 |
} |
| 35 |
|
| 36 |
public function verify(string $data, Key $key, string $signature): bool |
| 37 |
{ |
| 38 |
$key = $this->handleKey($key); |
| 39 |
|
| 40 |
return openssl_verify($data, $signature, $key->toPublic()->asPem(), $this->getHashAlgorithm()) === 1; |
| 41 |
} |
| 42 |
|
| 43 |
abstract protected function getHashAlgorithm(): int; |
| 44 |
|
| 45 |
private function handleKey(Key $key): RsaKey |
| 46 |
{ |
| 47 |
return RsaKey::create($key->getData()); |
| 48 |
} |
| 49 |
} |