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

RSAPKCS1   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 46
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A allowedKeyTypes() 0 4 1
A verify() 0 7 1
A sign() 0 16 3
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 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
    public function sign(JWK $key, string $input): string
37
    {
38
        $this->checkKey($key);
39
        if (!$key->has('d')) {
40
            throw new InvalidArgumentException('The key is not a private key.');
41
        }
42
43
        $priv = RSAKey::createFromJWK($key);
44
45
        $result = openssl_sign($input, $signature, $priv->toPEM(), $this->getAlgorithm());
46
        if (true !== $result) {
47
            throw new RuntimeException('Unable to sign');
48
        }
49
50
        return $signature;
51
    }
52
53
    abstract protected function getAlgorithm(): string;
54
55
    private function checkKey(JWK $key): void
56
    {
57
        if (!\in_array($key->get('kty'), $this->allowedKeyTypes(), true)) {
58
            throw new InvalidArgumentException('Wrong key type.');
59
        }
60
        foreach (['n', 'e'] as $k) {
61
            if (!$key->has($k)) {
62
                throw new InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k));
63
            }
64
        }
65
    }
66
}
67