OpenSSL::hashingAlgorithm()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 1
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
3
namespace Zenstruck\JWT\Signer;
4
5
use Zenstruck\JWT\Signer;
6
use Zenstruck\JWT\Signer\OpenSSL\Key;
7
use Zenstruck\JWT\Signer\OpenSSL\Keychain;
8
use Zenstruck\JWT\Signer\OpenSSL\PrivateKey;
9
use Zenstruck\JWT\Signer\OpenSSL\PublicKey;
10
11
/**
12
 * @author Alessandro Nadalin <[email protected]>
13
 * @author Kevin Bond <[email protected]>
14
 */
15
abstract class OpenSSL implements Signer
16
{
17 18
    public function __construct()
18
    {
19 18
        if (!extension_loaded('openssl')) {
20
            throw new \RuntimeException('The openssl PHP extension must be enabled to use RSA/ECDSA signers');
21
        }
22 18
    }
23
24
    /**
25
     * {@inheritdoc}
26
     */
27 12
    public function sign($input, $key)
28
    {
29 12
        if ($key instanceof Keychain) {
30 6
            $key = $key->privateKey();
31 6
        }
32
33 12
        if (!$key instanceof PrivateKey) {
34 6
            $key = new PrivateKey($key);
35 6
        }
36
37 12
        $this->verifyType($key);
38
39 12
        openssl_sign($input, $signature, $key->get(), $this->hashingAlgorithm());
40
41 12
        return $signature;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 12
    public function verify($input, $signature, $key)
48
    {
49 12
        if ($key instanceof Keychain) {
50 3
            $key = $key->publicKey();
51 3
        }
52
53 12
        if (!$key instanceof PublicKey) {
54 9
            $key = new PublicKey($key);
55 9
        }
56
57 12
        $result = openssl_verify($input, $signature, $key->get(), $this->hashingAlgorithm());
58
59 12
        if (-1 === $result) {
60
            throw new \RuntimeException('Unknown error during verification.');
61
        }
62
63 12
        return (bool) $result;
64
    }
65
66
    /**
67
     * @return int
68
     */
69
    abstract protected function hashingAlgorithm();
70
71
    /**
72
     * @return int
73
     */
74
    abstract protected function allowedType();
75
76
    /**
77
     * @param Key $key
78
     */
79 12
    private function verifyType(Key $key)
80
    {
81 12
        if ($this->allowedType() !== $key->type()) {
82
            throw new \InvalidArgumentException(sprintf('Invalid key type.'));
83
        }
84 12
    }
85
}
86