Completed
Push — master ( d7b29d...16c2f9 )
by Florent
02:46
created

Ed25519::checkKey()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
rs 8.8571
cc 5
eloc 7
nc 4
nop 1
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 Base64Url\Base64Url;
15
use Jose\Algorithm\SignatureAlgorithmInterface;
16
use Jose\Object\JWKInterface;
17
18
/**
19
 * Class Ed25519.
20
 */
21
class Ed25519 implements SignatureAlgorithmInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function sign(JWKInterface $key, $data)
27
    {
28
        $this->checkKey($key);
29
        if (!$key->has('d')) {
30
            throw new \InvalidArgumentException('The key is not private');
31
        }
32
33
        $secret = Base64Url::decode($key->get('d'));
34
        $public = Base64Url::decode($key->get('x'));
35
36
        $signature = ed25519_sign($data, $secret, $public);
37
38
        return $signature;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function verify(JWKInterface $key, $data, $signature)
45
    {
46
        $this->checkKey($key);
47
48
        $public = Base64Url::decode($key->get('x'));
49
50
        return ed25519_sign_open($data,  $public, $signature);
51
    }
52
53
    /**
54
     * @param JWKInterface $key
55
     */
56
    private function checkKey(JWKInterface $key)
57
    {
58
        if ('OKP' !== $key->get('kty')) {
59
            throw new \InvalidArgumentException('The key is not valid');
60
        }
61
        if (!$key->has('x') || !$key->has('crv')) {
62
            throw new \InvalidArgumentException('Key components ("x" or "crv") missing');
63
        }
64
        if ('Ed25519' !== $key->get('crv')) {
65
            throw new \InvalidArgumentException('Unsupported curve');
66
        }
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getAlgorithmName()
73
    {
74
        return 'Ed25519';
75
    }
76
}
77