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