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