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

Certificate   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 12
c 3
b 0
f 0
dl 0
loc 50
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A hasValidStructure() 0 3 1
A convertToCertificate() 0 5 1
A stripHeaders() 0 10 2
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