Failed Conditions
Push — v7 ( e9e51b...d9c0af )
by Florent
03:20
created

EdDSA::checkKey()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 8
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 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 Base64Url\Base64Url;
17
use Jose\Component\Core\JWK;
18
use Jose\Component\Signature\SignatureAlgorithmInterface;
19
20
/**
21
 * Class Ed25519.
22
 */
23
final class EdDSA implements SignatureAlgorithmInterface
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function sign(JWK $key, string $input): string
29
    {
30
        $this->checkKey($key);
31
        if (!$key->has('d')) {
32
            throw new \InvalidArgumentException('The key is not private.');
33
        }
34
        $secret = Base64Url::decode($key->get('d'));
35
        $keyPair = sodium_crypto_sign_seed_keypair($secret);
36
        $secretKey = sodium_crypto_sign_secretkey($keyPair);
37
38
        switch ($key->get('crv')) {
39
            case 'Ed25519':
40
                return sodium_crypto_sign_detached($input, $secretKey);
41
            default:
42
                throw new \InvalidArgumentException('Unsupported curve');
43
        }
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function verify(JWK $key, string $input, string $signature): bool
50
    {
51
        $this->checkKey($key);
52
53
        $public = Base64Url::decode($key->get('x'));
54
55
        switch ($key->get('crv')) {
56
            case 'Ed25519':
57
                return sodium_crypto_sign_verify_detached($signature, $input, $public);
58
            default:
59
                throw new \InvalidArgumentException('Unsupported curve');
60
        }
61
    }
62
63
    /**
64
     * @param JWK $key
65
     */
66
    private function checkKey(JWK $key)
67
    {
68
        if ('OKP' !== $key->get('kty')) {
69
            throw new \InvalidArgumentException('Wrong key type.');
70
        }
71
        foreach (['x', 'crv'] as $k) {
72
            if (!$key->has($k)) {
73
                throw new \InvalidArgumentException(sprintf('The key parameter "%s" is missing.', $k));
74
            }
75
        }
76
        if (!in_array($key->get('crv'), ['Ed25519'])) {
77
            throw new \InvalidArgumentException('Unsupported curve.');
78
        }
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function name(): string
85
    {
86
        return 'EdDSA';
87
    }
88
}
89