Passed
Push — master ( bf67e8...626507 )
by Milad
02:27
created

EdDsaVerifier::kid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace MiladRahimi\Jwt\Cryptography\Algorithms\Eddsa;
4
5
use MiladRahimi\Jwt\Cryptography\Keys\EdDsaPublicKey;
6
use MiladRahimi\Jwt\Cryptography\Verifier;
7
use MiladRahimi\Jwt\Exceptions\InvalidSignatureException;
8
use RuntimeException;
9
use SodiumException;
10
11
class EdDsaVerifier implements Verifier
12
{
13
    protected static string $name = 'EdDSA';
14
15
    protected EdDsaPublicKey $publicKey;
16
17
    public function __construct(EdDsaPublicKey $publicKey)
18
    {
19
        $this->publicKey = $publicKey;
20
    }
21
22
    /**
23
     * @inheritdoc
24
     */
25
    public function verify(string $plain, string $signature): void
26
    {
27
        if (function_exists('sodium_crypto_sign_verify_detached')) {
28
            try {
29
                if (!sodium_crypto_sign_verify_detached($signature, $plain, $this->publicKey->getContent())) {
30
                    throw new InvalidSignatureException('Signature is to verified');
31
                }
32
            } catch (SodiumException $e) {
33
                throw new InvalidSignatureException('Sodium cannot verify the signature', 0, $e);
34
            }
35
        } else {
36
            throw new RuntimeException('sodium_crypto_sign_verify_detached function is not available');
37
        }
38
    }
39
40
    public function name(): string
41
    {
42
        return static::$name;
43
    }
44
45
    /**
46
     * @inheritDoc
47
     */
48
    public function kid(): ?string
49
    {
50
        return $this->publicKey->getId();
51
    }
52
53
    public function getPublicKey(): EdDsaPublicKey
54
    {
55
        return $this->publicKey;
56
    }
57
}
58