Passed
Pull Request — master (#3)
by Tim
02:37
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
/**
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
    /**
23
     * @param string $certificate
24
     * @param string $pattern
25
     *
26
     * @return bool
27
     */
28
    public static function hasValidStructure(string $certificate, string $pattern = self::PUBLIC_KEY_PATTERN): bool
29
    {
30
        return !!preg_match($pattern, $certificate);
31
    }
32
33
34
    /**
35
     * @param string $X509CertificateContents
36
     *
37
     * @return string
38
     */
39
    public static function convertToCertificate(string $X509CertificateContents): string
40
    {
41
        return "-----BEGIN CERTIFICATE-----\n"
42
                . chunk_split($X509CertificateContents, 64, "\n")
43
                . "-----END CERTIFICATE-----";
44
    }
45
46
47
    /**
48
     * @param string $key The PEM-encoded key
49
     * @param string $pattern The pattern to use
50
     * @return string The stripped key
51
     */
52
    public static function stripHeaders(string $key, string $pattern = self::PUBLIC_KEY_PATTERN)
53
    {
54
        $matches = [];
55
        $result = preg_match($pattern, $key, $matches);
56
        if ($result === false) {
57
            throw new Exception('Could not find content matching the provided pattern.');
58
        }
59
60
        /** @psalm-suppress EmptyArrayAccess */
61
        return preg_replace('/\s+/', '', $matches[1]);
62
    }
63
}
64