Completed
Pull Request — master (#69)
by
unknown
03:32 queued 33s
created

Convert::pubkeyToPem()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

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