AESGCM::getIVSize()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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
/**
19
 * Class AESGCM.
20
 */
21
abstract class AESGCM implements ContentEncryptionAlgorithmInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function allowedKeyTypes(): array
27
    {
28
        return ['oct'];
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function encryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, ?string &$tag): string
35
    {
36
        $calculated_aad = $encoded_protected_header;
37
        if (null !== $aad) {
38
            $calculated_aad .= '.'.$aad;
39
        }
40
41
        $mode = sprintf('aes-%d-gcm', $this->getKeySize());
42
        $C = openssl_encrypt($data, $mode, $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad);
43
        if (false === $C) {
44
            throw new \InvalidArgumentException('Unable to encrypt the data.');
45
        }
46
47
        return $C;
48
    }
49
50
    /**
51
     *  {@inheritdoc}
52
     */
53
    public function decryptContent(string $data, string $cek, string $iv, ?string $aad, string $encoded_protected_header, string $tag): string
54
    {
55
        $calculated_aad = $encoded_protected_header;
56
        if (null !== $aad) {
57
            $calculated_aad .= '.'.$aad;
58
        }
59
60
        $mode = sprintf('aes-%d-gcm', $this->getKeySize());
61
        $P = openssl_decrypt($data, $mode, $cek, OPENSSL_RAW_DATA, $iv, $tag, $calculated_aad);
62
        if (false === $P) {
63
            throw new \InvalidArgumentException('Unable to decrypt or to verify the tag.');
64
        }
65
66
        return $P;
67
    }
68
69
    /**
70
     * @return int
71
     */
72
    public function getIVSize(): int
73
    {
74
        return 96;
75
    }
76
77
    /**
78
     * @return int
79
     */
80
    public function getCEKSize(): int
81
    {
82
        return $this->getKeySize();
83
    }
84
85
    /**
86
     * @return int
87
     */
88
    abstract protected function getKeySize(): int;
89
}
90