| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
/* |
| 6 |
* The MIT License (MIT) |
| 7 |
* |
| 8 |
* Copyright (c) 2014-2021 Spomky-Labs |
| 9 |
* |
| 10 |
* This software may be modified and distributed under the terms |
| 11 |
* of the MIT license. See the LICENSE file for details. |
| 12 |
*/ |
| 13 |
|
| 14 |
namespace WP_DEFENDER_VENDOR\Cose\Algorithm\Signature\ECDSA; |
| 15 |
|
| 16 |
use WP_DEFENDER_VENDOR\Assert\Assertion; |
| 17 |
use WP_DEFENDER_VENDOR\Cose\Algorithm\Signature\Signature; |
| 18 |
use WP_DEFENDER_VENDOR\Cose\Key\Ec2Key; |
| 19 |
use WP_DEFENDER_VENDOR\Cose\Key\Key; |
| 20 |
|
| 21 |
abstract class ECDSA implements Signature |
| 22 |
{ |
| 23 |
public function sign(string $data, Key $key): string |
| 24 |
{ |
| 25 |
$key = $this->handleKey($key); |
| 26 |
openssl_sign($data, $signature, $key->asPEM(), $this->getHashAlgorithm()); |
| 27 |
|
| 28 |
return ECSignature::fromAsn1($signature, $this->getSignaturePartLength()); |
| 29 |
} |
| 30 |
|
| 31 |
public function verify(string $data, Key $key, string $signature): bool |
| 32 |
{ |
| 33 |
$key = $this->handleKey($key); |
| 34 |
$publicKey = $key->toPublic(); |
| 35 |
$signature = ECSignature::toAsn1($signature, $this->getSignaturePartLength()); |
| 36 |
|
| 37 |
return 1 === openssl_verify($data, $signature, $publicKey->asPEM(), $this->getHashAlgorithm()); |
| 38 |
} |
| 39 |
|
| 40 |
abstract protected function getCurve(): int; |
| 41 |
|
| 42 |
abstract protected function getHashAlgorithm(): int; |
| 43 |
|
| 44 |
abstract protected function getSignaturePartLength(): int; |
| 45 |
|
| 46 |
private function handleKey(Key $key): Ec2Key |
| 47 |
{ |
| 48 |
$key = new Ec2Key($key->getData()); |
| 49 |
Assertion::eq($key->curve(), $this->getCurve(), 'This key cannot be used with this algorithm'); |
| 50 |
|
| 51 |
return $key; |
| 52 |
} |
| 53 |
} |
| 54 |
|