1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\JWX\JWS\Algorithm; |
6
|
|
|
|
7
|
|
|
use Sop\JWX\JWA\JWA; |
8
|
|
|
use Sop\JWX\JWK\JWK; |
9
|
|
|
use Sop\JWX\JWK\RSA\RSAPrivateKeyJWK; |
10
|
|
|
use Sop\JWX\JWK\RSA\RSAPublicKeyJWK; |
11
|
|
|
use Sop\JWX\JWS\SignatureAlgorithm; |
12
|
|
|
use Sop\JWX\JWT\Header\Header; |
13
|
|
|
use Sop\JWX\JWT\Parameter\AlgorithmParameter; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Base class for algorithms implementing signature with PKCS #1. |
17
|
|
|
* |
18
|
|
|
* @see https://tools.ietf.org/html/rfc7518#section-3.3 |
19
|
|
|
*/ |
20
|
|
|
abstract class RSASSAPKCS1Algorithm extends OpenSSLSignatureAlgorithm |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* Mapping from algorithm name to class name. |
24
|
|
|
* |
25
|
|
|
* @internal |
26
|
|
|
* |
27
|
|
|
* @var array |
28
|
|
|
*/ |
29
|
|
|
public const MAP_ALGO_TO_CLASS = [ |
30
|
|
|
JWA::ALGO_RS256 => RS256Algorithm::class, |
31
|
|
|
JWA::ALGO_RS384 => RS384Algorithm::class, |
32
|
|
|
JWA::ALGO_RS512 => RS512Algorithm::class, |
33
|
|
|
]; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Constructor. |
37
|
|
|
* |
38
|
|
|
* @param RSAPrivateKeyJWK $priv_key |
39
|
|
|
*/ |
40
|
10 |
|
protected function __construct(RSAPublicKeyJWK $pub_key, |
41
|
|
|
RSAPrivateKeyJWK $priv_key = null) |
42
|
|
|
{ |
43
|
10 |
|
$this->_publicKey = $pub_key; |
44
|
10 |
|
$this->_privateKey = $priv_key; |
45
|
10 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Initialize from a public key. |
49
|
|
|
*/ |
50
|
2 |
|
public static function fromPublicKey(RSAPublicKeyJWK $jwk): self |
51
|
|
|
{ |
52
|
2 |
|
return new static($jwk); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Initialize from a private key. |
57
|
|
|
*/ |
58
|
8 |
|
public static function fromPrivateKey(RSAPrivateKeyJWK $jwk): self |
59
|
|
|
{ |
60
|
8 |
|
return new static($jwk->publicKey(), $jwk); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* {@inheritdoc} |
65
|
|
|
* |
66
|
|
|
* @return self |
67
|
|
|
*/ |
68
|
5 |
|
public static function fromJWK(JWK $jwk, Header $header): SignatureAlgorithm |
69
|
|
|
{ |
70
|
5 |
|
$alg = JWA::deriveAlgorithmName($header, $jwk); |
71
|
5 |
|
if (!array_key_exists($alg, self::MAP_ALGO_TO_CLASS)) { |
72
|
1 |
|
throw new \UnexpectedValueException("Unsupported algorithm '{$alg}'."); |
73
|
|
|
} |
74
|
4 |
|
$cls = self::MAP_ALGO_TO_CLASS[$alg]; |
75
|
4 |
|
if ($jwk->has(...RSAPrivateKeyJWK::MANAGED_PARAMS)) { |
76
|
2 |
|
return $cls::fromPrivateKey(RSAPrivateKeyJWK::fromJWK($jwk)); |
77
|
|
|
} |
78
|
2 |
|
return $cls::fromPublicKey(RSAPublicKeyJWK::fromJWK($jwk)); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* {@inheritdoc} |
83
|
|
|
*/ |
84
|
2 |
|
public function headerParameters(): array |
85
|
|
|
{ |
86
|
2 |
|
return array_merge(parent::headerParameters(), |
87
|
2 |
|
[AlgorithmParameter::fromAlgorithm($this)]); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|