1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MadWizard\WebAuthn\Crypto; |
4
|
|
|
|
5
|
|
|
use MadWizard\WebAuthn\Exception\UnsupportedException; |
6
|
|
|
use MadWizard\WebAuthn\Exception\WebAuthnException; |
7
|
|
|
|
8
|
|
|
class OpenSslVerifier |
9
|
|
|
{ |
10
|
|
|
private const OPENSSL_ALGO_MAP = [ |
11
|
|
|
CoseAlgorithm::ES256 => OPENSSL_ALGO_SHA256, |
12
|
|
|
CoseAlgorithm::ES384 => OPENSSL_ALGO_SHA384, |
13
|
|
|
CoseAlgorithm::ES512 => OPENSSL_ALGO_SHA512, |
14
|
|
|
|
15
|
|
|
CoseAlgorithm::RS256 => OPENSSL_ALGO_SHA256, |
16
|
|
|
CoseAlgorithm::RS384 => OPENSSL_ALGO_SHA384, |
17
|
|
|
CoseAlgorithm::RS512 => OPENSSL_ALGO_SHA512, |
18
|
|
|
CoseAlgorithm::RS1 => OPENSSL_ALGO_SHA1, |
19
|
|
|
]; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var int |
23
|
|
|
*/ |
24
|
|
|
private $openSslAlgorithm; |
25
|
|
|
|
26
|
12 |
|
public function __construct(int $coseAlgorithm) |
27
|
|
|
{ |
28
|
12 |
|
$this->openSslAlgorithm = $this->getOpenSslAlgorithm($coseAlgorithm); |
29
|
12 |
|
} |
30
|
|
|
|
31
|
12 |
|
private function getOpenSslAlgorithm(int $algorithm): int |
32
|
|
|
{ |
33
|
12 |
|
$openSslAlgorithm = self::OPENSSL_ALGO_MAP[$algorithm] ?? null; |
34
|
|
|
|
35
|
12 |
|
if ($openSslAlgorithm === null) { |
36
|
|
|
throw new UnsupportedException('Unsupported algorithm'); |
37
|
|
|
} |
38
|
|
|
|
39
|
12 |
|
return $openSslAlgorithm; |
40
|
|
|
} |
41
|
|
|
|
42
|
12 |
|
public function verify(string $data, string $signature, string $keyPem): bool |
43
|
|
|
{ |
44
|
12 |
|
$publicKey = openssl_pkey_get_public($keyPem); |
45
|
12 |
|
if ($publicKey === false) { |
46
|
|
|
throw new WebAuthnException('Public key invalid'); |
47
|
|
|
} |
48
|
|
|
try { |
49
|
12 |
|
$verify = openssl_verify($data, $signature, $publicKey, $this->openSslAlgorithm); |
50
|
12 |
|
if ($verify === 1) { |
51
|
9 |
|
return true; |
52
|
|
|
} |
53
|
5 |
|
if ($verify === 0) { |
54
|
4 |
|
return false; |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
throw new WebAuthnException('Failed to check signature'); |
58
|
|
|
} finally { |
59
|
12 |
|
if (PHP_VERSION_ID < 80000) { |
60
|
12 |
|
openssl_free_key($publicKey); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|