1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\CertificateChain; |
4
|
|
|
|
5
|
|
|
use phpseclib\File\X509; |
6
|
|
|
use Spatie\CertificateChain\Exceptions\CouldNotCreateCertificate; |
7
|
|
|
|
8
|
|
|
class Certificate |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @param string The contents of the certificate |
12
|
|
|
*/ |
13
|
|
|
protected $contents; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param string $inputFile |
17
|
|
|
* |
18
|
|
|
* @return static |
19
|
|
|
*/ |
20
|
|
|
public static function loadFromFile(string $inputFile) |
21
|
|
|
{ |
22
|
|
|
return new static(file_get_contents($inputFile)); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param string $url |
27
|
|
|
* |
28
|
|
|
* @return static |
29
|
|
|
*/ |
30
|
|
|
public static function loadFromUrl(string $url) |
31
|
|
|
{ |
32
|
|
|
return static::loadFromFile($url); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function __construct(string $contents) |
36
|
|
|
{ |
37
|
|
|
$this->guardAgainstInvalidContents($contents); |
38
|
|
|
|
39
|
|
|
$this->contents = $contents; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Get the URL of the parent certificate. |
44
|
|
|
*/ |
45
|
|
|
public function getParentCertificateUrl(): string |
46
|
|
|
{ |
47
|
|
|
$x509 = new X509(); |
48
|
|
|
|
49
|
|
|
$certProperties = $x509->loadX509($this->contents); |
50
|
|
|
|
51
|
|
|
foreach ($certProperties['tbsCertificate']['extensions'] as $extension) { |
52
|
|
|
if ($extension['extnId'] == 'id-pe-authorityInfoAccess') { |
53
|
|
|
foreach ($extension['extnValue'] as $extnValue) { |
54
|
|
|
if ($extnValue['accessMethod'] == 'id-ad-caIssuers') { |
55
|
|
|
return $extnValue['accessLocation']['uniformResourceIdentifier']; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return ''; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function fetchParentCertificate(): Certificate |
65
|
|
|
{ |
66
|
|
|
return static::loadFromUrl($this->getParentCertificateUrl()); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
public function hasParentInTrustChain(): bool |
70
|
|
|
{ |
71
|
|
|
return ! $this->getParentCertificateUrl() == ''; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function getContents(): string |
75
|
|
|
{ |
76
|
|
|
$x509 = new X509(); |
77
|
|
|
|
78
|
|
|
return $x509->saveX509($x509->loadX509($this->contents)).PHP_EOL; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
protected function guardAgainstInvalidContents(string $content) |
82
|
|
|
{ |
83
|
|
|
if (! (new X509())->loadX509($content)) { |
84
|
|
|
throw CouldNotCreateCertificate::invalidContent($content); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|