1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace SimpleSAML\XMLSecurity\Utils; |
6
|
|
|
|
7
|
|
|
use Exception; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Collection of Utility functions specifically for certificates |
11
|
|
|
*/ |
12
|
|
|
class Certificate |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* The pattern that the contents of a certificate should adhere to |
16
|
|
|
*/ |
17
|
|
|
public const PUBLIC_KEY_PATTERN = '/^-----BEGIN CERTIFICATE-----([^-]*)^-----END CERTIFICATE-----/m'; |
18
|
|
|
public const PRIVATE_KEY_PATTERN = '/^-----BEGIN RSA PRIVATE KEY-----([^-]*)^-----END RSA PRIVATE KEY-----/m'; |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param string $certificate |
23
|
|
|
* @param string $pattern |
24
|
|
|
* |
25
|
|
|
* @return bool |
26
|
|
|
*/ |
27
|
|
|
public static function hasValidStructure(string $certificate, string $pattern = self::PUBLIC_KEY_PATTERN): bool |
28
|
|
|
{ |
29
|
|
|
return !!preg_match($pattern, $certificate); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param string $X509CertificateContents |
35
|
|
|
* |
36
|
|
|
* @return string |
37
|
|
|
*/ |
38
|
|
|
public static function convertToCertificate(string $X509CertificateContents): string |
39
|
|
|
{ |
40
|
|
|
return "-----BEGIN CERTIFICATE-----\n" |
41
|
|
|
. chunk_split($X509CertificateContents, 64, "\n") |
42
|
|
|
. "-----END CERTIFICATE-----"; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param array|string $issuer |
48
|
|
|
* |
49
|
|
|
* @return string |
50
|
|
|
*/ |
51
|
|
|
public static function parseIssuer($issuer): string |
52
|
|
|
{ |
53
|
|
|
if (is_array($issuer)) { |
54
|
|
|
$parts = []; |
55
|
|
|
foreach ($issuer as $key => $value) { |
56
|
|
|
array_unshift($parts, $key . '=' . $value); |
57
|
|
|
} |
58
|
|
|
return implode(',', $parts); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $issuer; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $key The PEM-encoded key |
67
|
|
|
* @param string $pattern The pattern to use |
68
|
|
|
* @return string The stripped key |
69
|
|
|
*/ |
70
|
|
|
public static function stripHeaders(string $key, string $pattern = self::PUBLIC_KEY_PATTERN) |
71
|
|
|
{ |
72
|
|
|
$matches = []; |
73
|
|
|
$result = preg_match($pattern, $key, $matches); |
74
|
|
|
if ($result === false) { |
75
|
|
|
throw new Exception('Could not find content matching the provided pattern.'); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** @psalm-suppress EmptyArrayAccess */ |
79
|
|
|
return preg_replace('/\s+/', '', $matches[1]); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|