PemPrivateKeySerializer   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 9 1
A parse() 0 8 1
A __construct() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Mdanter\Ecc\Serializer\PrivateKey;
5
6
use Mdanter\Ecc\Crypto\Key\PrivateKeyInterface;
7
8
/**
9
 * PEM Private key formatter
10
 *
11
 * @link https://tools.ietf.org/html/rfc5915
12
 */
13
class PemPrivateKeySerializer implements PrivateKeySerializerInterface
14
{
15
    /**
16
     * @var DerPrivateKeySerializer
17
     */
18
    private $derSerializer;
19
20
    /**
21
     * @param DerPrivateKeySerializer $derSerializer
22
     */
23
    public function __construct(DerPrivateKeySerializer $derSerializer)
24
    {
25
        $this->derSerializer = $derSerializer;
26
    }
27
28
    /**
29
     * {@inheritDoc}
30
     * @see \Mdanter\Ecc\Serializer\PrivateKey\PrivateKeySerializerInterface::serialize()
31
     */
32
    public function serialize(PrivateKeyInterface $key): string
33
    {
34
        $privateKeyInfo = $this->derSerializer->serialize($key);
35
36
        $content  = '-----BEGIN EC PRIVATE KEY-----'.PHP_EOL;
37
        $content .= trim(chunk_split(base64_encode($privateKeyInfo), 64, PHP_EOL)).PHP_EOL;
38
        $content .= '-----END EC PRIVATE KEY-----';
39
40
        return $content;
41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     * @see \Mdanter\Ecc\Serializer\PrivateKey\PrivateKeySerializerInterface::parse()
46
     */
47
    public function parse(string $formattedKey): PrivateKeyInterface
48
    {
49
        $formattedKey = str_replace('-----BEGIN EC PRIVATE KEY-----', '', $formattedKey);
50
        $formattedKey = str_replace('-----END EC PRIVATE KEY-----', '', $formattedKey);
51
52
        $data = base64_decode($formattedKey);
53
54
        return $this->derSerializer->parse($data);
55
    }
56
}
57