1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MadWizard\WebAuthn\Pki; |
4
|
|
|
|
5
|
|
|
use MadWizard\WebAuthn\Exception\ParseException; |
6
|
|
|
use MadWizard\WebAuthn\Format\SerializableTrait; |
7
|
|
|
use Serializable; |
8
|
|
|
|
9
|
|
|
final class X509Certificate implements Serializable |
10
|
|
|
{ |
11
|
|
|
use SerializableTrait; |
12
|
|
|
|
13
|
|
|
private const BEGIN_CERTIFICATE = '-----BEGIN CERTIFICATE-----'; |
14
|
|
|
|
15
|
|
|
private const END_CERTIFICATE = '-----END CERTIFICATE-----'; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
private $base64; |
21
|
|
|
|
22
|
23 |
|
private function __construct(string $base64) |
23
|
|
|
{ |
24
|
23 |
|
$this->base64 = $base64; |
25
|
23 |
|
} |
26
|
|
|
|
27
|
|
|
public function equals(X509Certificate $cert): bool |
28
|
|
|
{ |
29
|
|
|
return $this->base64 === $cert->base64; |
30
|
|
|
} |
31
|
|
|
|
32
|
15 |
|
public static function fromDer(string $der): self |
33
|
|
|
{ |
34
|
15 |
|
return new self(base64_encode($der)); |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
public static function fromPem(string $pem): self |
38
|
|
|
{ |
39
|
2 |
|
$start = strpos($pem, self::BEGIN_CERTIFICATE); |
40
|
2 |
|
$end = strpos($pem, self::END_CERTIFICATE); |
41
|
2 |
|
if ($start === false || $end === false) { |
42
|
|
|
throw new ParseException('Missing certificate PEM armor.'); |
43
|
|
|
} |
44
|
2 |
|
$start += strlen(self::BEGIN_CERTIFICATE); |
45
|
2 |
|
$base64 = substr($pem, $start, $end - $start); |
46
|
2 |
|
$base64 = preg_replace('~\s+~', '', $base64); |
47
|
2 |
|
return self::fromBase64($base64); |
48
|
|
|
} |
49
|
|
|
|
50
|
8 |
|
public static function fromBase64(string $base64): self |
51
|
|
|
{ |
52
|
8 |
|
$decoded = base64_decode($base64, true); |
53
|
8 |
|
if ($decoded === false) { |
54
|
|
|
throw new ParseException('Invalid base64 encoding in PEM certificate.'); |
55
|
|
|
} |
56
|
8 |
|
return new X509Certificate(base64_encode($decoded)); |
57
|
|
|
} |
58
|
|
|
|
59
|
5 |
|
public function asDer(): string |
60
|
|
|
{ |
61
|
5 |
|
$binary = base64_decode($this->base64, true); |
62
|
5 |
|
assert(is_string($binary)); |
63
|
5 |
|
return $binary; |
64
|
|
|
} |
65
|
|
|
|
66
|
20 |
|
public function asPem(): string |
67
|
|
|
{ |
68
|
|
|
return "-----BEGIN CERTIFICATE-----\n" . |
69
|
20 |
|
chunk_split($this->base64, 64, "\n") . |
70
|
20 |
|
"-----END CERTIFICATE-----\n"; |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
public function __serialize(): array |
74
|
|
|
{ |
75
|
1 |
|
return ['b' => $this->base64]; |
76
|
|
|
} |
77
|
|
|
|
78
|
1 |
|
public function __unserialize(array $data): void |
79
|
|
|
{ |
80
|
1 |
|
$this->base64 = $data['b']; |
81
|
1 |
|
} |
82
|
|
|
} |
83
|
|
|
|