1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Mdanter\Ecc\Serializer\PublicKey\Der; |
5
|
|
|
|
6
|
|
|
use FG\ASN1\Universal\Sequence; |
7
|
|
|
use FG\ASN1\Universal\ObjectIdentifier; |
8
|
|
|
use FG\ASN1\Universal\BitString; |
9
|
|
|
use Mdanter\Ecc\Primitives\PointInterface; |
10
|
|
|
use Mdanter\Ecc\Crypto\Key\PublicKeyInterface; |
11
|
|
|
use Mdanter\Ecc\Curves\NamedCurveFp; |
12
|
|
|
use Mdanter\Ecc\Serializer\Util\CurveOidMapper; |
13
|
|
|
use Mdanter\Ecc\Serializer\PublicKey\DerPublicKeySerializer; |
14
|
|
|
use Mdanter\Ecc\Serializer\Point\PointSerializerInterface; |
15
|
|
|
use Mdanter\Ecc\Serializer\Point\UncompressedPointSerializer; |
16
|
|
|
|
17
|
|
|
class Formatter |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var UncompressedPointSerializer |
21
|
|
|
*/ |
22
|
|
|
private $pointSerializer; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Formatter constructor. |
26
|
|
|
* @param PointSerializerInterface|null $pointSerializer |
27
|
|
|
*/ |
28
|
|
|
public function __construct(PointSerializerInterface $pointSerializer = null) |
29
|
|
|
{ |
30
|
|
|
$this->pointSerializer = $pointSerializer ?: new UncompressedPointSerializer(); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param PublicKeyInterface $key |
35
|
|
|
* @return string |
36
|
|
|
*/ |
37
|
|
|
public function format(PublicKeyInterface $key): string |
38
|
|
|
{ |
39
|
|
|
if (! ($key->getCurve() instanceof NamedCurveFp)) { |
40
|
|
|
throw new \RuntimeException('Not implemented for unnamed curves'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$sequence = new Sequence( |
44
|
|
|
new Sequence( |
45
|
|
|
new ObjectIdentifier(DerPublicKeySerializer::X509_ECDSA_OID), |
46
|
|
|
CurveOidMapper::getCurveOid($key->getCurve()) |
47
|
|
|
), |
48
|
|
|
new BitString($this->encodePoint($key->getPoint())) |
49
|
|
|
); |
50
|
|
|
|
51
|
|
|
return $sequence->getBinary(); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param PointInterface $point |
56
|
|
|
* @return string |
57
|
|
|
*/ |
58
|
|
|
public function encodePoint(PointInterface $point): string |
59
|
|
|
{ |
60
|
|
|
return $this->pointSerializer->serialize($point); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|