1 | <?php |
||
14 | class PublicKeySerializer implements PublicKeySerializerInterface |
||
15 | { |
||
16 | /** |
||
17 | * @var EcAdapter |
||
18 | */ |
||
19 | private $ecAdapter; |
||
20 | |||
21 | /** |
||
22 | * @param EcAdapter $ecAdapter |
||
23 | */ |
||
24 | 348 | public function __construct(EcAdapter $ecAdapter) |
|
28 | |||
29 | /** |
||
30 | * @param PublicKey $publicKey |
||
31 | * @return string |
||
32 | */ |
||
33 | 188 | public function getPrefix(PublicKey $publicKey) |
|
34 | { |
||
35 | 188 | if (null === $publicKey->getPrefix()) { |
|
36 | 98 | return $publicKey->isCompressed() |
|
37 | 66 | ? $this->ecAdapter->getMath()->isEven($publicKey->getPoint()->getY()) |
|
38 | 31 | ? PublicKey::KEY_COMPRESSED_EVEN |
|
39 | 66 | : PublicKey::KEY_COMPRESSED_ODD |
|
40 | 98 | : PublicKey::KEY_UNCOMPRESSED; |
|
41 | } else { |
||
42 | 112 | return $publicKey->getPrefix(); |
|
43 | } |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * @param PublicKey $publicKey |
||
48 | * @return BufferInterface |
||
49 | */ |
||
50 | 188 | private function doSerialize(PublicKey $publicKey) |
|
51 | { |
||
52 | 188 | $math = $this->ecAdapter->getMath(); |
|
53 | 188 | $point = $publicKey->getPoint(); |
|
54 | 188 | $compressed = $publicKey->isCompressed(); |
|
55 | |||
56 | 188 | $parser = new Parser('', $math); |
|
57 | 188 | $parser->writeBytes(1, new Buffer($this->getPrefix($publicKey))); |
|
58 | |||
59 | 188 | $compressed |
|
60 | ? $parser |
||
61 | 110 | ->writeBytes(32, Buffer::int(gmp_strval($point->getX(), 10), null, $math)) |
|
62 | : $parser |
||
63 | 96 | ->writeBytes(32, Buffer::int(gmp_strval($point->getX(), 10), null, $math)) |
|
64 | 96 | ->writeBytes(32, Buffer::int(gmp_strval($point->getY(), 10), null, $math)); |
|
65 | |||
66 | 188 | return $parser->getBuffer(); |
|
67 | } |
||
68 | |||
69 | /** |
||
70 | * @param PublicKeyInterface $publicKey |
||
71 | * @return BufferInterface |
||
72 | */ |
||
73 | 188 | public function serialize(PublicKeyInterface $publicKey) |
|
78 | |||
79 | /** |
||
80 | * @param BufferInterface|string $data |
||
81 | * @return PublicKey |
||
82 | * @throws \Exception |
||
83 | */ |
||
84 | 282 | public function parse($data) |
|
93 | } |
||
94 |