Failed Conditions
Push — v7 ( e446d4...9b9adb )
by Florent
02:29
created

AESGCM::checkKeyLength()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\Encryption\Algorithm\ContentEncryption;
15
16
use Jose\Component\Encryption\Algorithm\ContentEncryptionAlgorithmInterface;
17
18
abstract class AESGCM implements ContentEncryptionAlgorithmInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23
    public function encryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, ?string &$tag): string
24
    {
25
        $calculated_aad = $encoded_protected_header;
26
        if (null !== $aad) {
27
            $calculated_aad .= '.'.$aad;
28
        }
29
30
        $mode = sprintf('aes-%d-gcm', $this->getKeySize());
31
        $C = openssl_encrypt($data, $mode, $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad);
32
        if (false === $C) {
33
            throw new \InvalidArgumentException('Unable to encrypt the data.');
34
        }
35
36
        return $C;
37
    }
38
39
    /**
40
     *  {@inheritdoc}
41
     */
42
    public function decryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, string $tag): string
43
    {
44
        $calculated_aad = $encoded_protected_header;
45
        if (null !== $aad) {
46
            $calculated_aad .= '.'.$aad;
47
        }
48
49
        $mode = sprintf('aes-%d-gcm', $this->getKeySize());
50
        $P = openssl_decrypt($data, $mode, $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad);
51
        if (false === $P) {
52
            throw new \InvalidArgumentException('Unable to decrypt or to verify the tag.');
53
        }
54
55
        return $P;
56
    }
57
58
    /**
59
     * @return int
60
     */
61
    public function getIVSize(): int
62
    {
63
        return 96;
64
    }
65
66
    /**
67
     * @return int
68
     */
69
    public function getCEKSize(): int
70
    {
71
        return $this->getKeySize();
72
    }
73
74
    /**
75
     * @return int
76
     */
77
    abstract protected function getKeySize(): int;
78
}
79