Failed Conditions
Push — ECKeyAndGCm ( 8d8cde )
by Florent
02:05
created

AESGCMKW::unwrapKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 3
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\KeyEncryption;
13
14
use AESGCM\AESGCM;
15
use Assert\Assertion;
16
use Base64Url\Base64Url;
17
use Jose\Object\JWKInterface;
18
19
/**
20
 * Class AESGCMKW.
21
 */
22
abstract class AESGCMKW implements KeyWrappingInterface
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function wrapKey(JWKInterface $key, $cek, array $complete_headers, array &$additional_headers)
28
    {
29
        $this->checkKey($key);
30
        $kek = Base64Url::decode($key->get('k'));
31
        $iv = random_bytes(96 / 8);
32
        $additional_headers['iv'] = Base64Url::encode($iv);
33
34
        list($encrypted_cek, $tag) = AESGCM::encrypt($kek, $iv, $cek, null);
35
        $additional_headers['tag'] = Base64Url::encode($tag);
36
37
        return $encrypted_cek;
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function unwrapKey(JWKInterface $key, $encrypted_cek, array $header)
44
    {
45
        $this->checkKey($key);
46
        $this->checkAdditionalParameters($header);
47
48
        $kek = Base64Url::decode($key->get('k'));
49
        $tag = Base64Url::decode($header['tag']);
50
        $iv = Base64Url::decode($header['iv']);
51
52
        return AESGCM::decrypt($kek, $iv, $encrypted_cek, null, $tag);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function getKeyManagementMode()
59
    {
60
        return self::MODE_WRAP;
61
    }
62
63
    /**
64
     * @param JWKInterface $key
65
     */
66
    protected function checkKey(JWKInterface $key)
67
    {
68
        Assertion::eq($key->get('kty'), 'oct', 'Wrong key type.');
69
        Assertion::true($key->has('k'), 'The key parameter "k" is missing.');
70
    }
71
72
    /**
73
     * @param array $header
74
     */
75
    protected function checkAdditionalParameters(array $header)
76
    {
77
        Assertion::keyExists($header, 'iv', 'Parameter "iv" is missing.');
78
        Assertion::keyExists($header, 'tag', 'Parameter "tag" is missing.');
79
    }
80
81
    /**
82
     * @return int
83
     */
84
    abstract protected function getKeySize();
85
}
86