/
OpenSslVerifier.php
64 lines (53 loc) · 1.78 KB
/
OpenSslVerifier.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
<?php
namespace MadWizard\WebAuthn\Crypto;
use MadWizard\WebAuthn\Exception\UnsupportedException;
use MadWizard\WebAuthn\Exception\WebAuthnException;
class OpenSslVerifier
{
private const OPENSSL_ALGO_MAP = [
CoseAlgorithm::ES256 => OPENSSL_ALGO_SHA256,
CoseAlgorithm::ES384 => OPENSSL_ALGO_SHA384,
CoseAlgorithm::ES512 => OPENSSL_ALGO_SHA512,
CoseAlgorithm::RS256 => OPENSSL_ALGO_SHA256,
CoseAlgorithm::RS384 => OPENSSL_ALGO_SHA384,
CoseAlgorithm::RS512 => OPENSSL_ALGO_SHA512,
CoseAlgorithm::RS1 => OPENSSL_ALGO_SHA1,
];
/**
* @var int
*/
private $openSslAlgorithm;
public function __construct(int $coseAlgorithm)
{
$this->openSslAlgorithm = $this->getOpenSslAlgorithm($coseAlgorithm);
}
private function getOpenSslAlgorithm(int $algorithm): int
{
$openSslAlgorithm = self::OPENSSL_ALGO_MAP[$algorithm] ?? null;
if ($openSslAlgorithm === null) {
throw new UnsupportedException('Unsupported algorithm');
}
return $openSslAlgorithm;
}
public function verify(string $data, string $signature, string $keyPem): bool
{
$publicKey = openssl_pkey_get_public($keyPem);
if ($publicKey === false) {
throw new WebAuthnException('Public key invalid');
}
try {
$verify = openssl_verify($data, $signature, $publicKey, $this->openSslAlgorithm);
if ($verify === 1) {
return true;
}
if ($verify === 0) {
return false;
}
throw new WebAuthnException('Failed to check signature');
} finally {
if (PHP_VERSION_ID < 80000) {
openssl_free_key($publicKey);
}
}
}
}