Completed
Pull Request — master (#70)
by
unknown
01:32
created

Convert::base64uDecode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace u2flib_server;
6
7
use ParagonIE\ConstantTime\Encoding;
8
9
/**
10
 * Class Convert
11
 *
12
 * @package u2flib_server
13
 */
14
class Convert
15
{
16
    /**
17
     * @param string $data
18
     *
19
     * @return string
20
     */
21
    public static function base64uEncode(string $data): string
22
    {
23
        return trim(strtr(Encoding::base64Encode($data), '+/', '-_'), '=');
24
    }
25
26
    /**
27
     * @param string $data
28
     *
29
     * @return string
30
     */
31
    public static function base64uDecode(string $data): string
32
    {
33
        return Encoding::base64Decode(strtr($data, '-_', '+/'));
34
    }
35
36
    /**
37
     * Convert the public key to binary DER format first
38
     * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
39
     *
40
     * @param string $key
41
     *
42
     * @return null|string
43
     */
44
    public static function pubkeyToPem(string $key)
45
    {
46
        if (strlen($key) !== PUBKEY_LEN || $key[0] !== "\x04") {
47
            return null;
48
        }
49
50
        /*
51
         * Convert the public key to binary DER format first
52
         * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
53
         *
54
         *  SEQUENCE(2 elem)                        30 59
55
         *   SEQUENCE(2 elem)                       30 13
56
         *    OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01
57
         *    OID1.2.840.10045.3.1.7 (secp256r1)    06 08 2a 86 48 ce 3d 03 01 07
58
         *   BIT STRING(520 bit)                    03 42 ..key..
59
         */
60
        $der = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01";
61
        $der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42";
62
        $der .= "\0" . $key;
63
64
        $pem = "-----BEGIN PUBLIC KEY-----\r\n";
65
        $pem .= chunk_split(Encoding::base64Encode($der), 64);
66
        $pem .= '-----END PUBLIC KEY-----';
67
68
        return $pem;
69
    }
70
}
71