Debian Codegraph @

lib/3rdParty/composer/web-token/jwt-library/Core/Util/ECKey.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jose\Component\Core\Util;
6
7 use InvalidArgumentException;
8 use Jose\Component\Core\JWK;
9 use RuntimeException;
10 use function extension_loaded;
11 use function is_array;
12 use function is_string;
13 use const OPENSSL_KEYTYPE_EC;
14 use const STR_PAD_LEFT;
15
16 /**
17 * @internal
18 */
19 final class ECKey
20 {
21 public static function convertToPEM(JWK $jwk): string
22 {
23 if ($jwk->has('d')) {
24 return self::convertPrivateKeyToPEM($jwk);
25 }
26
27 return self::convertPublicKeyToPEM($jwk);
28 }
29
30 public static function convertPublicKeyToPEM(JWK $jwk): string
31 {
32 $der = match ($jwk->get('crv')) {
33 'P-256' => self::p256PublicKey(),
34 'secp256k1' => self::p256KPublicKey(),
35 'P-384' => self::p384PublicKey(),
36 'P-521' => self::p521PublicKey(),
37 default => throw new InvalidArgumentException('Unsupported curve.'),
38 };
39 $der .= self::getKey($jwk);
40 $pem = '-----BEGIN PUBLIC KEY-----' . "\n";
41 $pem .= chunk_split(base64_encode($der), 64, "\n");
42
43 return $pem . ('-----END PUBLIC KEY-----' . "\n");
44 }
45
46 public static function convertPrivateKeyToPEM(JWK $jwk): string
47 {
48 $der = match ($jwk->get('crv')) {
49 'P-256' => self::p256PrivateKey($jwk),
50 'secp256k1' => self::p256KPrivateKey($jwk),
51 'P-384' => self::p384PrivateKey($jwk),
52 'P-521' => self::p521PrivateKey($jwk),
53 default => throw new InvalidArgumentException('Unsupported curve.'),
54 };
55 $der .= self::getKey($jwk);
56 $pem = '-----BEGIN EC PRIVATE KEY-----' . "\n";
57 $pem .= chunk_split(base64_encode($der), 64, "\n");
58
59 return $pem . ('-----END EC PRIVATE KEY-----' . "\n");
60 }
61
62 /**
63 * Creates a EC key with the given curve and additional values.
64 *
65 * @param string $curve The curve
66 * @param array $values values to configure the key
67 */
68 public static function createECKey(string $curve, array $values = []): JWK
69 {
70 $jwk = self::createECKeyUsingOpenSSL($curve);
71 $values = array_merge($values, $jwk);
72
73 return new JWK($values);
74 }
75
76 private static function getNistCurveSize(string $curve): int
77 {
78 return match ($curve) {
79 'P-256', 'secp256k1' => 256,
80 'P-384' => 384,
81 'P-521' => 521,
82 default => throw new InvalidArgumentException(sprintf('The curve "%s" is not supported.', $curve)),
83 };
84 }
85
86 private static function createECKeyUsingOpenSSL(string $curve): array
87 {
88 if (! extension_loaded('openssl')) {
89 throw new RuntimeException('Please install the OpenSSL extension');
90 }
91 $key = openssl_pkey_new([
92 'curve_name' => self::getOpensslCurveName($curve),
93 'private_key_type' => OPENSSL_KEYTYPE_EC,
94 ]);
95 if ($key === false) {
96 throw new RuntimeException('Unable to create the key');
97 }
98 $result = openssl_pkey_export($key, $out);
99 if ($result === false) {
100 throw new RuntimeException('Unable to create the key');
101 }
102 $res = openssl_pkey_get_private($out);
103 if ($res === false) {
104 throw new RuntimeException('Unable to create the key');
105 }
106 $details = openssl_pkey_get_details($res);
107 if ($details === false) {
108 throw new InvalidArgumentException('Unable to get the key details');
109 }
110 $nistCurveSize = self::getNistCurveSize($curve);
111
112 return [
113 'kty' => 'EC',
114 'crv' => $curve,
115 'd' => Base64UrlSafe::encodeUnpadded(
116 str_pad((string) $details['ec']['d'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)
117 ),
118 'x' => Base64UrlSafe::encodeUnpadded(
119 str_pad((string) $details['ec']['x'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)
120 ),
121 'y' => Base64UrlSafe::encodeUnpadded(
122 str_pad((string) $details['ec']['y'], (int) ceil($nistCurveSize / 8), "\0", STR_PAD_LEFT)
123 ),
124 ];
125 }
126
127 private static function getOpensslCurveName(string $curve): string
128 {
129 return match ($curve) {
130 'P-256' => 'prime256v1',
131 'secp256k1' => 'secp256k1',
132 'P-384' => 'secp384r1',
133 'P-521' => 'secp521r1',
134 default => throw new InvalidArgumentException(sprintf('The curve "%s" is not supported.', $curve)),
135 };
136 }
137
138 private static function p256PublicKey(): string
139 {
140 return pack(
141 'H*',
142 '3059' // SEQUENCE, length 89
143 . '3013' // SEQUENCE, length 19
144 . '0607' // OID, length 7
145 . '2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
146 . '0608' // OID, length 8
147 . '2a8648ce3d030107' // 1.2.840.10045.3.1.7 = P-256 Curve
148 . '0342' // BIT STRING, length 66
149 . '00' // prepend with NUL - pubkey will follow
150 );
151 }
152
153 private static function p256KPublicKey(): string
154 {
155 return pack(
156 'H*',
157 '3056' // SEQUENCE, length 86
158 . '3010' // SEQUENCE, length 16
159 . '0607' // OID, length 7
160 . '2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
161 . '0605' // OID, length 8
162 . '2B8104000A' // 1.3.132.0.10 secp256k1
163 . '0342' // BIT STRING, length 66
164 . '00' // prepend with NUL - pubkey will follow
165 );
166 }
167
168 private static function p384PublicKey(): string
169 {
170 return pack(
171 'H*',
172 '3076' // SEQUENCE, length 118
173 . '3010' // SEQUENCE, length 16
174 . '0607' // OID, length 7
175 . '2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
176 . '0605' // OID, length 5
177 . '2b81040022' // 1.3.132.0.34 = P-384 Curve
178 . '0362' // BIT STRING, length 98
179 . '00' // prepend with NUL - pubkey will follow
180 );
181 }
182
183 private static function p521PublicKey(): string
184 {
185 return pack(
186 'H*',
187 '30819b' // SEQUENCE, length 154
188 . '3010' // SEQUENCE, length 16
189 . '0607' // OID, length 7
190 . '2a8648ce3d0201' // 1.2.840.10045.2.1 = EC Public Key
191 . '0605' // OID, length 5
192 . '2b81040023' // 1.3.132.0.35 = P-521 Curve
193 . '038186' // BIT STRING, length 134
194 . '00' // prepend with NUL - pubkey will follow
195 );
196 }
197
198 private static function p256PrivateKey(JWK $jwk): string
199 {
200 $d = $jwk->get('d');
201 if (! is_string($d)) {
202 throw new InvalidArgumentException('Unable to get the private key');
203 }
204 $d = unpack('H*', str_pad(Base64UrlSafe::decodeNoPadding($d), 32, "\0", STR_PAD_LEFT));
205 if (! is_array($d) || ! isset($d[1])) {
206 throw new InvalidArgumentException('Unable to get the private key');
207 }
208
209 return pack(
210 'H*',
211 '3077' // SEQUENCE, length 87+length($d)=32
212 . '020101' // INTEGER, 1
213 . '0420' // OCTET STRING, length($d) = 32
214 . $d[1]
215 . 'a00a' // TAGGED OBJECT #0, length 10
216 . '0608' // OID, length 8
217 . '2a8648ce3d030107' // 1.3.132.0.34 = P-256 Curve
218 . 'a144' // TAGGED OBJECT #1, length 68
219 . '0342' // BIT STRING, length 66
220 . '00' // prepend with NUL - pubkey will follow
221 );
222 }
223
224 private static function p256KPrivateKey(JWK $jwk): string
225 {
226 $d = $jwk->get('d');
227 if (! is_string($d)) {
228 throw new InvalidArgumentException('Unable to get the private key');
229 }
230 $d = unpack('H*', str_pad(Base64UrlSafe::decodeNoPadding($d), 32, "\0", STR_PAD_LEFT));
231 if (! is_array($d) || ! isset($d[1])) {
232 throw new InvalidArgumentException('Unable to get the private key');
233 }
234
235 return pack(
236 'H*',
237 '3074' // SEQUENCE, length 84+length($d)=32
238 . '020101' // INTEGER, 1
239 . '0420' // OCTET STRING, length($d) = 32
240 . $d[1]
241 . 'a007' // TAGGED OBJECT #0, length 7
242 . '0605' // OID, length 5
243 . '2b8104000a' // 1.3.132.0.10 secp256k1
244 . 'a144' // TAGGED OBJECT #1, length 68
245 . '0342' // BIT STRING, length 66
246 . '00' // prepend with NUL - pubkey will follow
247 );
248 }
249
250 private static function p384PrivateKey(JWK $jwk): string
251 {
252 $d = $jwk->get('d');
253 if (! is_string($d)) {
254 throw new InvalidArgumentException('Unable to get the private key');
255 }
256 $d = unpack('H*', str_pad(Base64UrlSafe::decodeNoPadding($d), 48, "\0", STR_PAD_LEFT));
257 if (! is_array($d) || ! isset($d[1])) {
258 throw new InvalidArgumentException('Unable to get the private key');
259 }
260
261 return pack(
262 'H*',
263 '3081a4' // SEQUENCE, length 116 + length($d)=48
264 . '020101' // INTEGER, 1
265 . '0430' // OCTET STRING, length($d) = 30
266 . $d[1]
267 . 'a007' // TAGGED OBJECT #0, length 7
268 . '0605' // OID, length 5
269 . '2b81040022' // 1.3.132.0.34 = P-384 Curve
270 . 'a164' // TAGGED OBJECT #1, length 100
271 . '0362' // BIT STRING, length 98
272 . '00' // prepend with NUL - pubkey will follow
273 );
274 }
275
276 private static function p521PrivateKey(JWK $jwk): string
277 {
278 $d = $jwk->get('d');
279 if (! is_string($d)) {
280 throw new InvalidArgumentException('Unable to get the private key');
281 }
282 $d = unpack('H*', str_pad(Base64UrlSafe::decodeNoPadding($d), 66, "\0", STR_PAD_LEFT));
283 if (! is_array($d) || ! isset($d[1])) {
284 throw new InvalidArgumentException('Unable to get the private key');
285 }
286
287 return pack(
288 'H*',
289 '3081dc' // SEQUENCE, length 154 + length($d)=66
290 . '020101' // INTEGER, 1
291 . '0442' // OCTET STRING, length(d) = 66
292 . $d[1]
293 . 'a007' // TAGGED OBJECT #0, length 7
294 . '0605' // OID, length 5
295 . '2b81040023' // 1.3.132.0.35 = P-521 Curve
296 . 'a18189' // TAGGED OBJECT #1, length 137
297 . '038186' // BIT STRING, length 134
298 . '00' // prepend with NUL - pubkey will follow
299 );
300 }
301
302 private static function getKey(JWK $jwk): string
303 {
304 $crv = $jwk->get('crv');
305 if (! is_string($crv)) {
306 throw new InvalidArgumentException('Unable to get the curve');
307 }
308 $nistCurveSize = self::getNistCurveSize($crv);
309 $length = (int) ceil($nistCurveSize / 8);
310 $x = $jwk->get('x');
311 if (! is_string($x)) {
312 throw new InvalidArgumentException('Unable to get the public key');
313 }
314 $y = $jwk->get('y');
315 if (! is_string($y)) {
316 throw new InvalidArgumentException('Unable to get the public key');
317 }
318 $binX = ltrim(Base64UrlSafe::decodeNoPadding($x), "\0");
319 $binY = ltrim(Base64UrlSafe::decodeNoPadding($y), "\0");
320
321 return "\04"
322 . str_pad($binX, $length, "\0", STR_PAD_LEFT)
323 . str_pad($binY, $length, "\0", STR_PAD_LEFT)
324 ;
325 }
326 }