Debian Codegraph @

lib/3rdParty/composer/web-auth/cose-lib/src/Algorithm/Signature/EdDSA/EdDSA.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Cose\Algorithm\Signature\EdDSA;
6
7 use Cose\Algorithm\Signature\Signature;
8 use Cose\Algorithms;
9 use Cose\Key\Key;
10 use Cose\Key\OkpKey;
11 use InvalidArgumentException;
12 use function sodium_crypto_sign_detached;
13 use function sodium_crypto_sign_verify_detached;
14 use Throwable;
15
16 /**
17 * @see \Cose\Tests\Algorithm\Signature\EdDSA\EdDSATest
18 */
19 class EdDSA implements Signature
20 {
21 public function sign(string $data, Key $key): string
22 {
23 $key = $this->handleKey($key);
24 if (! $key->isPrivate()) {
25 throw new InvalidArgumentException('The key is not private.');
26 }
27
28 $x = $key->x();
29 $d = $key->d();
30 $secret = $d . $x;
31
32 return match ($key->curve()) {
33 OkpKey::CURVE_ED25519 => sodium_crypto_sign_detached($data, $secret),
34 OkpKey::CURVE_NAME_ED25519 => sodium_crypto_sign_detached($data, $secret),
35 default => throw new InvalidArgumentException('Unsupported curve'),
36 };
37 }
38
39 public function verify(string $data, Key $key, string $signature): bool
40 {
41 $key = $this->handleKey($key);
42 if ($key->curve() !== OkpKey::CURVE_ED25519 && $key->curve() !== OkpKey::CURVE_NAME_ED25519) {
43 throw new InvalidArgumentException('Unsupported curve');
44 }
45 try {
46 return sodium_crypto_sign_verify_detached($signature, $data, $key->x());
47 } catch (Throwable) {
48 return false;
49 }
50 }
51
52 public static function identifier(): int
53 {
54 return Algorithms::COSE_ALGORITHM_EDDSA;
55 }
56
57 private function handleKey(Key $key): OkpKey
58 {
59 return OkpKey::create($key->getData());
60 }
61 }