Debian Codegraph @

lib/3rdParty/composer/web-auth/cose-lib/src/Key/OkpKey.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Cose\Key;
6
7 use function array_key_exists;
8 use function in_array;
9 use InvalidArgumentException;
10
11 /**
12 * @final
13 * @see \Cose\Tests\Key\OkpKeyTest
14 */
15 class OkpKey extends Key
16 {
17 final public const CURVE_X25519 = 4;
18
19 final public const CURVE_X448 = 5;
20
21 final public const CURVE_ED25519 = 6;
22
23 final public const CURVE_ED448 = 7;
24
25 final public const CURVE_NAME_X25519 = 'X25519';
26
27 final public const CURVE_NAME_X448 = 'X448';
28
29 final public const CURVE_NAME_ED25519 = 'Ed25519';
30
31 final public const CURVE_NAME_ED448 = 'Ed448';
32
33 final public const DATA_CURVE = -1;
34
35 final public const DATA_X = -2;
36
37 final public const DATA_D = -4;
38
39 private const SUPPORTED_CURVES_INT = [
40 self::CURVE_X25519,
41 self::CURVE_X448,
42 self::CURVE_ED25519,
43 self::CURVE_ED448,
44 ];
45
46 private const SUPPORTED_CURVES_NAME = [
47 self::CURVE_NAME_X25519,
48 self::CURVE_NAME_X448,
49 self::CURVE_NAME_ED25519,
50 self::CURVE_NAME_ED448,
51 ];
52
53 /**
54 * @param array<int|string, mixed> $data
55 */
56 public function __construct(array $data)
57 {
58 foreach ([self::DATA_CURVE, self::TYPE] as $key) {
59 if (is_numeric($data[$key])) {
60 $data[$key] = (int) $data[$key];
61 }
62 }
63 parent::__construct($data);
64 if ($data[self::TYPE] !== self::TYPE_OKP && $data[self::TYPE] !== self::TYPE_NAME_OKP) {
65 throw new InvalidArgumentException('Invalid OKP key. The key type does not correspond to an OKP key');
66 }
67 if (! isset($data[self::DATA_CURVE], $data[self::DATA_X])) {
68 throw new InvalidArgumentException('Invalid EC2 key. The curve or the "x" coordinate is missing');
69 }
70 if (is_numeric($data[self::DATA_CURVE])) {
71 if (! in_array((int) $data[self::DATA_CURVE], self::SUPPORTED_CURVES_INT, true)) {
72 throw new InvalidArgumentException('The curve is not supported');
73 }
74 } elseif (! in_array($data[self::DATA_CURVE], self::SUPPORTED_CURVES_NAME, true)) {
75 throw new InvalidArgumentException('The curve is not supported');
76 }
77 }
78
79 /**
80 * @param array<int|string, mixed> $data
81 */
82 public static function create(array $data): self
83 {
84 return new self($data);
85 }
86
87 public function x(): string
88 {
89 return $this->get(self::DATA_X);
90 }
91
92 public function isPrivate(): bool
93 {
94 return array_key_exists(self::DATA_D, $this->getData());
95 }
96
97 public function d(): string
98 {
99 if (! $this->isPrivate()) {
100 throw new InvalidArgumentException('The key is not private.');
101 }
102
103 return $this->get(self::DATA_D);
104 }
105
106 public function curve(): int|string
107 {
108 return $this->get(self::DATA_CURVE);
109 }
110 }