|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Strobotti\JWK; |
| 6 | + |
| 7 | +use phpseclib\Crypt\RSA; |
| 8 | +use phpseclib\Math\BigInteger; |
| 9 | + |
| 10 | +/** |
| 11 | + * @package Strobotti\JWK |
| 12 | + * @author Juha Jantunen <[email protected]> |
| 13 | + * @license https://opensource.org/licenses/MIT MIT |
| 14 | + * @link https://github.com/Strobotti/php-jwk |
| 15 | + */ |
| 16 | +class Converter |
| 17 | +{ |
| 18 | + /** |
| 19 | + * @param Key $key |
| 20 | + * |
| 21 | + * @return string |
| 22 | + */ |
| 23 | + public function keyToPem(Key $key): string |
| 24 | + { |
| 25 | + // TODO implement strategies to support different key types |
| 26 | + $rsa = new RSA(); |
| 27 | + |
| 28 | + $modulus = $this->base64UrlDecode($key->getRsaModulus(), true); |
| 29 | + |
| 30 | + $rsa->loadKey([ |
| 31 | + 'e' => new BigInteger(\base64_decode($key->getRsaExponent(), true), 256), |
| 32 | + 'n' => new BigInteger($modulus, 256), |
| 33 | + ]); |
| 34 | + |
| 35 | + return $rsa->getPublicKey(); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @param string $pem A PEM encoded (RSA) Public Key |
| 40 | + * @param array $options An array of key-options, such as ['kid' => 'eXaunmL', 'use' => 'sig', ...] |
| 41 | + * |
| 42 | + * @return Key |
| 43 | + */ |
| 44 | + public function pemToKey(string $pem, array $options = []): Key |
| 45 | + { |
| 46 | + $keyInfo = openssl_pkey_get_details(openssl_pkey_get_public($pem)); |
| 47 | + |
| 48 | + $jsonData = array_merge( |
| 49 | + $options, |
| 50 | + [ |
| 51 | + 'kty' => 'RSA', |
| 52 | + 'n' => $this->base64UrlEncode($keyInfo['rsa']['n']), |
| 53 | + 'e' => $this->base64UrlEncode($keyInfo['rsa']['e']), |
| 54 | + ] |
| 55 | + ); |
| 56 | + |
| 57 | + return Key::createFromJSON(json_encode($jsonData)); |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * https://tools.ietf.org/html/rfc4648#section-5. |
| 62 | + * |
| 63 | + * @param string $data |
| 64 | + * @param bool $strict |
| 65 | + * |
| 66 | + * @return string |
| 67 | + */ |
| 68 | + private function base64UrlDecode(string $data, $strict = false): string |
| 69 | + { |
| 70 | + $b64 = \strtr($data, '-_', '+/'); |
| 71 | + |
| 72 | + return \base64_decode($b64, $strict); |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * https://tools.ietf.org/html/rfc4648#section-5. |
| 77 | + * |
| 78 | + * @param string $data |
| 79 | + * |
| 80 | + * @return string |
| 81 | + */ |
| 82 | + private function base64UrlEncode(string $data): string |
| 83 | + { |
| 84 | + return rtrim(\strtr(\base64_encode($data), '+/', '-_'), '='); |
| 85 | + } |
| 86 | +} |
0 commit comments