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

RSAPKCS1::allowedKeyTypes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
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 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