-
Notifications
You must be signed in to change notification settings - Fork 108
/
UncompressedPointSerializer.php
78 lines (64 loc) · 2.23 KB
/
UncompressedPointSerializer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace Mdanter\Ecc\Serializer\Point;
use Mdanter\Ecc\Primitives\PointInterface;
use Mdanter\Ecc\Primitives\CurveFpInterface;
use Mdanter\Ecc\Serializer\Util\CurveOidMapper;
use Mdanter\Ecc\Math\MathAdapterInterface;
class UncompressedPointSerializer implements PointSerializerInterface
{
/**
* @var MathAdapterInterface
*/
private $adapter;
/**
* @var bool
*/
private $debug = false;
/**
* @param MathAdapterInterface $adapter
* @param bool $debug
*/
public function __construct(MathAdapterInterface $adapter, $debug = false)
{
$this->adapter = $adapter;
$this->debug = (bool) $debug;
}
/**
* @param PointInterface $point
* @return string
*/
public function serialize(PointInterface $point)
{
$length = CurveOidMapper::getByteSize($point->getCurve()) * 2;
if ($this->debug) {
error_log('Detected length: '.$length);
error_log('Unpadded:'.$this->adapter->decHex($point->getX()));
error_log('Unpadded len:'.strlen($this->adapter->decHex($point->getX())));
error_log('Padded: '.str_pad($this->adapter->decHex($point->getX()), $length, '0', STR_PAD_LEFT));
}
$hexString = '04';
$hexString .= str_pad($this->adapter->decHex($point->getX()), $length, '0', STR_PAD_LEFT);
$hexString .= str_pad($this->adapter->decHex($point->getY()), $length, '0', STR_PAD_LEFT);
if ($this->debug) {
error_log('Resulting length: '.strlen($hexString));
error_log('Hex: '.$hexString);
}
return $hexString;
}
/**
* @param CurveFpInterface $curve
* @param string $data
* @return PointInterface
*/
public function unserialize(CurveFpInterface $curve, $data)
{
if (substr($data, 0, 2) != '04') {
throw new \InvalidArgumentException('Invalid data: only uncompressed keys are supported.');
}
$data = substr($data, 2);
$dataLength = strlen($data);
$x = $this->adapter->hexDec(substr($data, 0, $dataLength / 2));
$y = $this->adapter->hexDec(substr($data, $dataLength / 2));
return $curve->getPoint($x, $y);
}
}