1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* The MIT License (MIT) |
7
|
|
|
* |
8
|
|
|
* Copyright (c) 2014-2019 Spomky-Labs |
9
|
|
|
* |
10
|
|
|
* This software may be modified and distributed under the terms |
11
|
|
|
* of the MIT license. See the LICENSE file for details. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Jose\Component\Signature\Algorithm; |
15
|
|
|
|
16
|
|
|
use InvalidArgumentException; |
17
|
|
|
use Jose\Component\Core\JWK; |
18
|
|
|
use Jose\Component\Core\Util\RSAKey; |
19
|
|
|
use RuntimeException; |
20
|
|
|
|
21
|
|
|
abstract class RSAPKCS1 implements SignatureAlgorithm |
22
|
|
|
{ |
23
|
|
|
public function allowedKeyTypes(): array |
24
|
|
|
{ |
25
|
|
|
return ['RSA']; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function verify(JWK $key, string $input, string $signature): bool |
29
|
|
|
{ |
30
|
|
|
$this->checkKey($key); |
31
|
|
|
$pub = RSAKey::createFromJWK($key->toPublic()); |
32
|
|
|
|
33
|
|
|
return 1 === openssl_verify($input, $signature, $pub->toPEM(), $this->getAlgorithm()); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @throws InvalidArgumentException if the key is not private |
38
|
|
|
* @throws InvalidArgumentException if the data cannot be signed |
39
|
|
|
*/ |
40
|
|
|
public function sign(JWK $key, string $input): string |
41
|
|
|
{ |
42
|
|
|
$this->checkKey($key); |
43
|
|
|
if (!$key->has('d')) { |
44
|
|
|
throw new InvalidArgumentException('The key is not a private key.'); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$priv = RSAKey::createFromJWK($key); |
48
|
|
|
|
49
|
|
|
$result = openssl_sign($input, $signature, $priv->toPEM(), $this->getAlgorithm()); |
50
|
|
|
if (true !== $result) { |
51
|
|
|
throw new RuntimeException('Unable to sign'); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $signature; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
abstract protected function getAlgorithm(): string; |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @throws InvalidArgumentException if the key type is not allowed |
61
|
|
|
* @throws InvalidArgumentException if the key is not valid |
62
|
|
|
*/ |
63
|
|
|
private function checkKey(JWK $key): void |
64
|
|
|
{ |
65
|
|
|
if (!\in_array($key->get('kty'), $this->allowedKeyTypes(), true)) { |
66
|
|
|
throw new InvalidArgumentException('Wrong key type.'); |
67
|
|
|
} |
68
|
|
|
foreach (['n', 'e'] as $k) { |
69
|
|
|
if (!$key->has($k)) { |
70
|
|
|
throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k)); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|