Completed
Push — master ( f6e8cb...e5bdab )
by Florent
02:48 queued 01:28
created

RSA::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
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 Jose\Component\Signature\Algorithm\Util\RSA as JoseRSA;
20
use RuntimeException;
21
22
/**
23
 * @deprecated Please use either RSAPSS or RSAPKCS1 depending on the padding mode
24
 */
25
abstract class RSA implements SignatureAlgorithm
26
{
27
    public function __construct()
28
    {
29
        if (!\extension_loaded('gmp')) {
30
            throw new RuntimeException(static::class.' requires gmp extension');
31
        }
32
    }
33
34
    public function allowedKeyTypes(): array
35
    {
36
        return ['RSA'];
37
    }
38
39
    public function verify(JWK $key, string $input, string $signature): bool
40
    {
41
        $this->checkKey($key);
42
        $pub = RSAKey::createFromJWK($key->toPublic());
43
44
        return JoseRSA::verify($pub, $input, $signature, $this->getAlgorithm(), $this->getSignatureMethod());
45
    }
46
47
    public function sign(JWK $key, string $input): string
48
    {
49
        $this->checkKey($key);
50
        if (!$key->has('d')) {
51
            throw new InvalidArgumentException('The key is not a private key.');
52
        }
53
54
        $priv = RSAKey::createFromJWK($key);
55
56
        return JoseRSA::sign($priv, $input, $this->getAlgorithm(), $this->getSignatureMethod());
57
    }
58
59
    abstract protected function getAlgorithm(): string;
60
61
    abstract protected function getSignatureMethod(): int;
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