1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Sop\GCM; |
6
|
|
|
|
7
|
|
|
use Sop\GCM\Cipher\AES\AESCipher; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Implements AES-GCM encryption. |
11
|
|
|
*/ |
12
|
|
|
abstract class AESGCM |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Encrypt plaintext. |
16
|
|
|
* |
17
|
|
|
* @param string $plaintext Plaintext to encrypt |
18
|
|
|
* @param string $aad Additional authenticated data |
19
|
|
|
* @param string $key Encryption key |
20
|
|
|
* @param string $iv Initialization vector |
21
|
|
|
* @return array Tuple of ciphertext and authentication tag |
22
|
|
|
*/ |
23
|
35 |
|
public static function encrypt(string $plaintext, string $aad, string $key, |
24
|
|
|
string $iv): array |
25
|
|
|
{ |
26
|
35 |
|
return self::_getGCM(strlen($key))->encrypt($plaintext, $aad, $key, $iv); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Decrypt ciphertext. |
31
|
|
|
* |
32
|
|
|
* @param string $ciphertext Ciphertext to decrypt |
33
|
|
|
* @param string $auth_tag Authentication tag to verify |
34
|
|
|
* @param string $aad Additional authenticated data |
35
|
|
|
* @param string $key Encryption key |
36
|
|
|
* @param string $iv Initialization vector |
37
|
|
|
* @throws \Sop\GCM\Exception\AuthenticationException If message |
38
|
|
|
* authentication fails |
39
|
|
|
* @return string Plaintext |
40
|
|
|
*/ |
41
|
35 |
|
public static function decrypt(string $ciphertext, string $auth_tag, |
42
|
|
|
string $aad, string $key, string $iv): string |
43
|
|
|
{ |
44
|
35 |
|
return self::_getGCM(strlen($key))->decrypt($ciphertext, $auth_tag, $aad, |
45
|
35 |
|
$key, $iv); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Get GCM instance. |
50
|
|
|
* |
51
|
|
|
* @param int $keylen Key length in bytes |
52
|
|
|
* @return GCM |
53
|
|
|
*/ |
54
|
36 |
|
protected static function _getGCM(int $keylen): GCM |
55
|
|
|
{ |
56
|
36 |
|
return new GCM(AESCipher::fromKeyLength($keylen)); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|