-
Notifications
You must be signed in to change notification settings - Fork 8
/
JWKConverter.php
82 lines (66 loc) · 2.08 KB
/
JWKConverter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/*
* This file is part of the JwkFromOidcToken package.
*
* (c) codercat <1067302838@qq.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CoderCat\JWKToPEM;
use phpseclib\Crypt\RSA;
use phpseclib\Math\BigInteger;
use CoderCat\JWKToPEM\Util\Base64UrlDecoder;
use CoderCat\JWKToPEM\Exception\JWKConverterException;
class JWKConverter
{
/** @var Base64UrlDecoder */
private $base64UrlDecoder;
public function __construct(Base64UrlDecoder $base64UrlDecoder = null)
{
$this->base64UrlDecoder = $base64UrlDecoder ?? new Base64UrlDecoder();
}
/**
* @param array $jwkSet
* @return string[]
* @throws JWKConverterException
* @throws Exception\Base64DecodeException
*/
public function multipleToPem(array $jwkSet): array
{
$keys = [];
foreach($jwkSet as $jwk) {
if(!is_array($jwk)) {
throw new JWKConverterException('`multipleToPem` can only take in an array of JWKs.');
}
$keys[] = $this->toPEM($jwk);
}
return $keys;
}
/**
* @param array $jwk
* @return string
* @throws Exception\Base64DecodeException
* @throws JWKConverterException
*/
public function toPEM(array $jwk): string
{
if (!array_key_exists('e', $jwk) || !array_key_exists('n', $jwk) || !array_key_exists('kty', $jwk)) {
throw new JWKConverterException();
}
if ($jwk['kty'] != 'RSA') {
throw new JWKConverterException('RSA key type is currently only supported.');
}
if (array_key_exists('d', $jwk)) {
throw new JWKConverterException('Public key is currently only supported.');
}
$rsa = new RSA();
$rsa->loadKey(
[
'e' => new BigInteger(base64_decode($jwk['e']), 256),
'n' => new BigInteger($this->base64UrlDecoder->decode($jwk['n']), 256)
]
);
return $rsa->getPublicKey();
}
}