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

EdDsaVerifier   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 45
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A verify() 0 12 4
A kid() 0 3 1
A getPublicKey() 0 3 1
A name() 0 3 1
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