xref: /dokuwiki/vendor/phpseclib/phpseclib/phpseclib/Crypt/Common/Formats/Keys/JWK.php (revision 927933f55f286c8bea68959a13975cbcb59eb8ee)
1<?php
2
3/**
4 * JSON Web Key (RFC7517) Handler
5 *
6 * PHP version 5
7 *
8 * @author    Jim Wigginton <terrafrost@php.net>
9 * @copyright 2015 Jim Wigginton
10 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
11 * @link      http://phpseclib.sourceforge.net
12 */
13
14namespace phpseclib3\Crypt\Common\Formats\Keys;
15
16use phpseclib3\Common\Functions\Strings;
17
18/**
19 * JSON Web Key Formatted Key Handler
20 *
21 * @author  Jim Wigginton <terrafrost@php.net>
22 */
23abstract class JWK
24{
25    /**
26     * Break a public or private key down into its constituent components
27     *
28     * @param string $key
29     * @param string $password
30     * @return array
31     */
32    public static function load($key, $password = '')
33    {
34        if (!Strings::is_stringable($key)) {
35            throw new \UnexpectedValueException('Key should be a string - not a ' . gettype($key));
36        }
37
38        $key = preg_replace('#\s#', '', $key); // remove whitespace
39
40        if (PHP_VERSION_ID >= 73000) {
41            $key = json_decode($key, null, 512, JSON_THROW_ON_ERROR);
42        } else {
43            $key = json_decode($key);
44            if (!$key) {
45                throw new \RuntimeException('Unable to decode JSON');
46            }
47        }
48
49        if (isset($key->kty)) {
50            return $key;
51        }
52
53        if (count($key->keys) != 1) {
54            throw new \RuntimeException('Although the JWK key format supports multiple keys phpseclib does not');
55        }
56
57        return $key->keys[0];
58    }
59
60    /**
61     * Wrap a key appropriately
62     *
63     * @return string
64     */
65    protected static function wrapKey(array $key, array $options)
66    {
67        return json_encode(['keys' => [$key + $options]]);
68    }
69}
70