Completed
Push — master ( 022625...2b82d4 )
by Florent
05:58
created

HMAC   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 4
Bugs 0 Features 2
Metric Value
wmc 3
c 4
b 0
f 2
lcom 1
cbo 3
dl 0
loc 34
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A checkKey() 0 5 1
getHashAlgorithm() 0 1 ?
A sign() 0 6 1
A verify() 0 4 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 Base64Url\Base64Url;
16
use Jose\Algorithm\SignatureAlgorithmInterface;
17
use Jose\Object\JWKInterface;
18
19
/**
20
 * This class handles signatures using HMAC.
21
 * It supports algorithms HS256, HS384 and HS512;.
22
 */
23
abstract class HMAC implements SignatureAlgorithmInterface
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function sign(JWKInterface $key, $input)
29
    {
30
        $this->checkKey($key);
31
32
        return hash_hmac($this->getHashAlgorithm(), $input, Base64Url::decode($key->get('k')), true);
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function verify(JWKInterface $key, $input, $signature)
39
    {
40
        return hash_equals($this->sign($key, $input), $signature);
41
    }
42
43
    /**
44
     * @param JWKInterface $key
45
     */
46
    protected function checkKey(JWKInterface $key)
47
    {
48
        Assertion::eq($key->get('kty'), 'oct', 'Wrong key type.');
49
        Assertion::true($key->has('k'), 'The key parameter "k" is missing.');
50
    }
51
52
    /**
53
     * @return string
54
     */
55
    abstract protected function getHashAlgorithm();
56
}
57