1 | <?php |
||
25 | abstract class ECDSA implements SignatureAlgorithmInterface |
||
26 | { |
||
27 | /** |
||
28 | * @var \Mdanter\Ecc\Math\MathAdapterInterface |
||
29 | */ |
||
30 | private $adapter; |
||
31 | |||
32 | public function __construct() |
||
33 | { |
||
34 | $this->adapter = EccFactory::getAdapter(); |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * {@inheritdoc} |
||
39 | */ |
||
40 | public function sign(JWKInterface $key, $data) |
||
63 | |||
64 | /** |
||
65 | * {@inheritdoc} |
||
66 | */ |
||
67 | public function verify(JWKInterface $key, $data, $signature) |
||
68 | { |
||
69 | $this->checkKey($key); |
||
70 | |||
71 | $signature = $this->convertBinToHex($signature); |
||
72 | $part_length = $this->getSignaturePartLength(); |
||
73 | if (mb_strlen($signature, '8bit') !== 2 * $part_length) { |
||
74 | return false; |
||
75 | } |
||
76 | |||
77 | $p = $this->getGenerator(); |
||
78 | $x = $this->convertBase64ToDec($key->get('x')); |
||
79 | $y = $this->convertBase64ToDec($key->get('y')); |
||
80 | $R = $this->convertHexToDec(mb_substr($signature, 0, $part_length, '8bit')); |
||
81 | $S = $this->convertHexToDec(mb_substr($signature, $part_length, null, '8bit')); |
||
82 | $hash = $this->convertHexToDec(hash($this->getHashAlgorithm(), $data)); |
||
83 | |||
84 | $public_key = $p->getPublicKeyFrom($x, $y); |
||
85 | |||
86 | $signer = EccFactory::getSigner(); |
||
87 | |||
88 | return $signer->verify($public_key, new Signature($R, $S), $hash); |
||
89 | } |
||
90 | |||
91 | /** |
||
92 | * @return \Mdanter\Ecc\Primitives\GeneratorPoint |
||
93 | */ |
||
94 | abstract protected function getGenerator(); |
||
95 | |||
96 | /** |
||
97 | * @return string |
||
98 | */ |
||
99 | abstract protected function getHashAlgorithm(); |
||
100 | |||
101 | /** |
||
102 | * @return int |
||
103 | */ |
||
104 | abstract protected function getSignaturePartLength(); |
||
105 | |||
106 | /** |
||
107 | * @param string $value |
||
108 | * |
||
109 | * @return string |
||
110 | */ |
||
111 | private function convertHexToBin($value) |
||
115 | |||
116 | /** |
||
117 | * @param string $value |
||
118 | */ |
||
119 | private function convertBinToHex($value) |
||
125 | |||
126 | /** |
||
127 | * @param $value |
||
128 | * |
||
129 | * @return string |
||
130 | */ |
||
131 | private function convertDecToHex($value) |
||
135 | |||
136 | /** |
||
137 | * @param $value |
||
138 | * |
||
139 | * @return int|string |
||
140 | */ |
||
141 | private function convertHexToDec($value) |
||
145 | |||
146 | /** |
||
147 | * @param $value |
||
148 | * |
||
149 | * @return int|string |
||
150 | */ |
||
151 | private function convertBase64ToDec($value) |
||
157 | |||
158 | /** |
||
159 | * @param JWKInterface $key |
||
160 | */ |
||
161 | private function checkKey(JWKInterface $key) |
||
168 | } |
||
169 |