|
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
|
|
|
* @param int $tag_length Authentication tag length in bytes |
|
22
|
|
|
* |
|
23
|
|
|
* @return array Tuple of ciphertext and authentication tag |
|
24
|
|
|
*/ |
|
25
|
42 |
|
public static function encrypt(string $plaintext, string $aad, string $key, |
|
26
|
|
|
string $iv, int $tag_length = 16): array |
|
27
|
|
|
{ |
|
28
|
42 |
|
$cipher = AESCipher::fromKeyLength(strlen($key)); |
|
29
|
42 |
|
if ($cipher->hasNativeCipher()) { |
|
30
|
42 |
|
return $cipher->nativeEncrypt($plaintext, $aad, $key, $iv, $tag_length); |
|
31
|
|
|
} |
|
32
|
|
|
return self::_getGCM($cipher, $tag_length) |
|
33
|
|
|
->encrypt($plaintext, $aad, $key, $iv); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Decrypt ciphertext. |
|
38
|
|
|
* |
|
39
|
|
|
* @param string $ciphertext Ciphertext to decrypt |
|
40
|
|
|
* @param string $auth_tag Authentication tag to verify |
|
41
|
|
|
* @param string $aad Additional authenticated data |
|
42
|
|
|
* @param string $key Encryption key |
|
43
|
|
|
* @param string $iv Initialization vector |
|
44
|
|
|
* |
|
45
|
|
|
* @throws \Sop\GCM\Exception\AuthenticationException If message authentication fails |
|
46
|
|
|
* |
|
47
|
|
|
* @return string Plaintext |
|
48
|
|
|
*/ |
|
49
|
42 |
|
public static function decrypt(string $ciphertext, string $auth_tag, |
|
50
|
|
|
string $aad, string $key, string $iv): string |
|
51
|
|
|
{ |
|
52
|
42 |
|
$cipher = AESCipher::fromKeyLength(strlen($key)); |
|
53
|
42 |
|
if ($cipher->hasNativeCipher()) { |
|
54
|
42 |
|
return $cipher->nativeDecrypt($ciphertext, $auth_tag, $aad, $key, $iv); |
|
55
|
|
|
} |
|
56
|
|
|
return self::_getGCM($cipher, strlen($auth_tag)) |
|
57
|
|
|
->decrypt($ciphertext, $auth_tag, $aad, $key, $iv); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Get GCM instance. |
|
62
|
|
|
* |
|
63
|
|
|
* @param AESCipher $cipher Cipher instance |
|
64
|
|
|
* @param int $tag_length Authentication tag length |
|
65
|
|
|
* |
|
66
|
|
|
* @return GCM |
|
67
|
|
|
*/ |
|
68
|
|
|
protected static function _getGCM(AESCipher $cipher, int $tag_length): GCM |
|
69
|
|
|
{ |
|
70
|
|
|
return new GCM($cipher, $tag_length); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|