Completed
Push — master ( 5a840a...243a46 )
by Florent
03:27
created

EdDSA::sign()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 2
eloc 10
nc 2
nop 2
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2016 Spomky-Labs
7
 *
8
 * This software may be modified and distributed under the terms
9
 * of the MIT license.  See the LICENSE file for details.
10
 */
11
12
namespace Jose\Algorithm\Signature;
13
14
use Assert\Assertion;
15
use Base64Url\Base64Url;
16
use Jose\Algorithm\SignatureAlgorithmInterface;
17
use Jose\Object\JWKInterface;
18
19
/**
20
 * Class Ed25519.
21
 */
22
class EdDSA implements SignatureAlgorithmInterface
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function sign(JWKInterface $key, $data)
28
    {
29
        $this->checkKey($key);
30
        Assertion::true($key->has('d'), 'The key is not private');
31
32
        $secret = Base64Url::decode($key->get('d'));
33
        $public = Base64Url::decode($key->get('x'));
34
35
        switch ($key->get('crv')) {
36
            case 'Ed25519':
37
                return ed25519_sign($data, $secret, $public);
38
            default:
39
                throw new \InvalidArgumentException('Unsupported curve');
40
        }
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function verify(JWKInterface $key, $data, $signature)
47
    {
48
        $this->checkKey($key);
49
50
        $public = Base64Url::decode($key->get('x'));
51
52
        switch ($key->get('crv')) {
53
            case 'Ed25519':
54
                return ed25519_sign_open($data, $public, $signature);
55
            default:
56
                throw new \InvalidArgumentException('Unsupported curve');
57
        }
58
    }
59
60
    /**
61
     * @param JWKInterface $key
62
     */
63
    private function checkKey(JWKInterface $key)
64
    {
65
        Assertion::eq($key->get('kty'), 'OKP', 'Wrong key type.');
66
        Assertion::true($key->has('x'), 'The key parameter "x" is missing.');
67
        Assertion::true($key->has('crv'), 'The key parameter "crv" is missing.');
68
        Assertion::inArray($key->get('crv'), ['Ed25519'], 'Unsupported curve');
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function getAlgorithmName()
75
    {
76
        return 'EdDSA';
77
    }
78
}
79