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

RSAPSS   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 48
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A allowedKeyTypes() 0 4 1
A verify() 0 7 1
A sign() 0 11 2
getAlgorithm() 0 1 ?
A checkKey() 0 11 4
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
abstract class RSAPSS implements SignatureAlgorithm
23
{
24
    public function __construct()
25
    {
26
        if (!\extension_loaded('gmp')) {
27
            throw new RuntimeException(static::class.' requires gmp extension');
28
        }
29
    }
30
31
    public function allowedKeyTypes(): array
32
    {
33
        return ['RSA'];
34
    }
35
36
    public function verify(JWK $key, string $input, string $signature): bool
37
    {
38
        $this->checkKey($key);
39
        $pub = RSAKey::createFromJWK($key->toPublic());
40
41
        return JoseRSA::verify($pub, $input, $signature, $this->getAlgorithm(), JoseRSA::SIGNATURE_PSS);
42
    }
43
44
    public function sign(JWK $key, string $input): string
45
    {
46
        $this->checkKey($key);
47
        if (!$key->has('d')) {
48
            throw new InvalidArgumentException('The key is not a private key.');
49
        }
50
51
        $priv = RSAKey::createFromJWK($key);
52
53
        return JoseRSA::sign($priv, $input, $this->getAlgorithm(), JoseRSA::SIGNATURE_PSS);
54
    }
55
56
    abstract protected function getAlgorithm(): string;
57
58
    private function checkKey(JWK $key): void
59
    {
60
        if (!\in_array($key->get('kty'), $this->allowedKeyTypes(), true)) {
61
            throw new InvalidArgumentException('Wrong key type.');
62
        }
63
        foreach (['n', 'e'] as $k) {
64
            if (!$key->has($k)) {
65
                throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k));
66
            }
67
        }
68
    }
69
}
70