RSA   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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

6 Methods

Rating   Name   Duplication   Size   Complexity  
getAlgorithm() 0 1 ?
getSignatureMethod() 0 1 ?
A verify() 0 7 1
A sign() 0 11 2
A checkKey() 0 11 4
A allowedKeyTypes() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 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 Jose\Component\Core\JWK;
17
use Jose\Component\Core\Util\RSAKey;
18
use Jose\Component\Signature\Util\RSA as JoseRSA;
19
20
/**
21
 * Class RSA.
22
 */
23
abstract class RSA implements SignatureAlgorithmInterface
24
{
25
    /**
26
     * @return mixed
27
     */
28
    abstract protected function getAlgorithm(): string;
29
30
    /**
31
     * @return int
32
     */
33
    abstract protected function getSignatureMethod(): int;
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function allowedKeyTypes(): array
39
    {
40
        return ['RSA'];
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function verify(JWK $key, string $input, string $signature): bool
47
    {
48
        $this->checkKey($key);
49
        $pub = RSAKey::createFromJWK($key->toPublic());
50
51
        return JoseRSA::verify($pub, $input, $signature, $this->getAlgorithm(), $this->getSignatureMethod());
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function sign(JWK $key, string $input): string
58
    {
59
        $this->checkKey($key);
60
        if (!$key->has('d')) {
61
            throw new \InvalidArgumentException('The key is not a private key.');
62
        }
63
64
        $priv = RSAKey::createFromJWK($key);
65
66
        return JoseRSA::sign($priv, $input, $this->getAlgorithm(), $this->getSignatureMethod());
67
    }
68
69
    /**
70
     * @param JWK $key
71
     */
72
    private function checkKey(JWK $key)
73
    {
74
        if ('RSA' !== $key->get('kty')) {
75
            throw new \InvalidArgumentException('Wrong key type.');
76
        }
77
        foreach (['n', 'e'] as $k) {
78
            if (!$key->has($k)) {
79
                throw new \InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k));
80
            }
81
        }
82
    }
83
}
84