Failed Conditions
Pull Request — master (#151)
by Florent
03:08
created

AESGCM::getCEKSize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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\ContentEncryption;
13
14
use AESGCM\AESGCM as GCM;
15
use Crypto\Cipher;
16
use Jose\Algorithm\ContentEncryptionAlgorithmInterface;
17
18
abstract class AESGCM implements ContentEncryptionAlgorithmInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function encryptContent($data, $cek, $iv, $aad, $encoded_protected_header, &$tag)
24
    {
25
        $calculated_aad = $encoded_protected_header;
26
        if (null !== $aad) {
27
            $calculated_aad .= '.'.$aad;
28
        }
29
30
        list($cyphertext, $tag) = GCM::encrypt($cek, $iv, $data, $calculated_aad);
31
32
        return $cyphertext;
33
    }
34
35
    /**
36
     *  {@inheritdoc}
37
     */
38
    public function decryptContent($data, $cek, $iv, $aad, $encoded_protected_header, $tag)
39
    {
40
        $calculated_aad = $encoded_protected_header;
41
        if (null !== $aad) {
42
            $calculated_aad .= '.'.$aad;
43
        }
44
45
        if (version_compare(PHP_VERSION, '7.1.0') >= 0) {
46
            return openssl_decrypt($data, $this->getMode($cek), $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad);
47
        } elseif (class_exists('\Crypto\Cipher')) {
48
            $cipher = Cipher::aes(Cipher::MODE_GCM, $this->getKeySize());
49
            $cipher->setTag($tag);
50
            $cipher->setAAD($calculated_aad);
51
52
            $plaintext = $cipher->decrypt($data, $cek, $iv);
53
54
            return $plaintext;
55
        }
56
57
        return GCM::decrypt($cek, $iv, $data, $calculated_aad, $tag);
58
    }
59
60
    /**
61
     * @param string $k
62
     *
63
     * @return string
64
     */
65
    private function getMode($k)
66
    {
67
        return 'aes-'.(8 * mb_strlen($k, '8bit')).'-gcm';
68
    }
69
70
    /**
71
     * @return int
72
     */
73
    public function getIVSize()
74
    {
75
        return 96;
76
    }
77
78
    /**
79
     * @return int
80
     */
81
    public function getCEKSize()
82
    {
83
        return $this->getKeySize();
84
    }
85
86
    /**
87
     * @return int
88
     */
89
    abstract protected function getKeySize();
90
}
91