Completed
Push — master ( 1a59c2...c73113 )
by Florent
02:55
created

RSA::checkKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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 Assert\Assertion;
15
use Jose\Algorithm\SignatureAlgorithmInterface;
16
use Jose\KeyConverter\KeyConverter;
17
use Jose\Object\JWKInterface;
18
use phpseclib\Crypt\RSA as PHPSecLibRSA;
19
20
/**
21
 * Class RSA.
22
 */
23
abstract class RSA implements SignatureAlgorithmInterface
24
{
25
    /**
26
     * @return mixed
27
     */
28
    abstract protected function getAlgorithm();
29
30
    /**
31
     * @return mixed
32
     */
33
    abstract protected function getSignatureMethod();
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function verify(JWKInterface $key, $input, $signature)
39
    {
40
        $this->checkKey($key);
41
42
        $values = array_intersect_key($key->getAll(), array_flip(['n', 'e']));
43
        $rsa = KeyConverter::fromArrayToRSACrypt($values);
44
45
        $rsa->setHash($this->getAlgorithm());
46
        if ($this->getSignatureMethod() === PHPSecLibRSA::SIGNATURE_PSS) {
47
            $rsa->setMGFHash($this->getAlgorithm());
48
            $rsa->setSaltLength(0);
49
        }
50
        $rsa->setSignatureMode($this->getSignatureMethod());
51
52
        return $rsa->verify($input, $signature);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function sign(JWKInterface $key, $input)
59
    {
60
        $this->checkKey($key);
61
62
        $values = array_intersect_key($key->getAll(), array_flip(['n', 'e', 'p', 'd', 'q', 'dp', 'dq', 'qi']));
63
        $rsa = KeyConverter::fromArrayToRSACrypt($values);
64
65
        if ($rsa->getPrivateKey() === false) {
66
            throw new \InvalidArgumentException('The key is not a private key');
67
        }
68
69
        $rsa->setHash($this->getAlgorithm());
70
        if ($this->getSignatureMethod() === PHPSecLibRSA::SIGNATURE_PSS) {
71
            $rsa->setMGFHash($this->getAlgorithm());
72
            $rsa->setSaltLength(0);
73
        }
74
        $rsa->setSignatureMode($this->getSignatureMethod());
75
76
        $result = $rsa->sign($input);
77
        Assertion::string($result, 'An error occurred during the creation of the signature');
78
79
        return $result;
80
    }
81
82
    /**
83
     * @param JWKInterface $key
84
     */
85
    protected function checkKey(JWKInterface $key)
86
    {
87
        Assertion::eq($key->get('kty'), 'RSA', 'Wrong key type.');
88
    }
89
}
90