Passed
Pull Request — master (#3)
by Tim
02:04
created

Certificate::stripHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XMLSecurity\Utils;
6
7
use Exception;
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 PUBLIC_KEY_PATTERN = '/^-----BEGIN CERTIFICATE-----([^-]*)^-----END CERTIFICATE-----/m';
24
    public const PRIVATE_KEY_PATTERN = '/^-----BEGIN RSA PRIVATE KEY-----([^-]*)^-----END RSA PRIVATE KEY-----/m';
25
26
27
    /**
28
     * @param string $certificate
29
     * @param string $pattern
30
     *
31
     * @return bool
32
     */
33
    public static function hasValidStructure(string $certificate, string $pattern = self::PUBLIC_KEY_PATTERN): bool
34
    {
35
        return !!preg_match($pattern, $certificate);
36
    }
37
38
39
    /**
40
     * @param string $X509CertificateContents
41
     *
42
     * @return string
43
     */
44
    public static function convertToCertificate(string $X509CertificateContents): string
45
    {
46
        return "-----BEGIN CERTIFICATE-----\n"
47
                . chunk_split($X509CertificateContents, 64, "\n")
48
                . "-----END CERTIFICATE-----";
49
    }
50
51
52
    /**
53
     * @param array|string $issuer
54
     *
55
     * @return string
56
     */
57
    public static function parseIssuer($issuer): string
58
    {
59
        if (is_array($issuer)) {
60
            $parts = [];
61
            foreach ($issuer as $key => $value) {
62
                array_unshift($parts, $key . '=' . $value);
63
            }
64
            return implode(',', $parts);
65
        }
66
67
        return $issuer;
68
    }
69
70
71
    /**
72
     * @param string $key The PEM-encoded key
73
     * @param string $pattern The pattern to use
74
     * @return string The stripped key
75
     */
76
    public static function stripHeaders(string $key, string $pattern = self::PUBLIC_KEY_PATTERN)
77
    {
78
        $matches = [];
79
        $result = preg_match($pattern, $key, $matches);
80
        if ($result === false) {
81
            throw new Exception('Could not find content matching the provided pattern.');
82
        }
83
84
        /** @psalm-suppress EmptyArrayAccess */
85
        return preg_replace('/\s+/', '', $matches[1]);
86
    }
87
}
88