1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Security; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Strings\StringHelper; |
8
|
|
|
|
9
|
|
|
final class Crypt |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var array[] Look-up table of block sizes and key sizes for each supported OpenSSL cipher. |
13
|
|
|
* |
14
|
|
|
* In each element, the key is one of the ciphers supported by OpenSSL {@see openssl_get_cipher_methods()}. |
15
|
|
|
* The value is an array of two integers, the first is the cipher's block size in bytes and the second is |
16
|
|
|
* the key size in bytes. |
17
|
|
|
* |
18
|
|
|
* > Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key |
19
|
|
|
* derivation salt. |
20
|
|
|
*/ |
21
|
|
|
private const ALLOWED_CIPHERS = [ |
22
|
|
|
'AES-128-CBC' => [16, 16], |
23
|
|
|
'AES-192-CBC' => [16, 24], |
24
|
|
|
'AES-256-CBC' => [16, 32], |
25
|
|
|
]; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var string The cipher to use for encryption and decryption. |
29
|
|
|
*/ |
30
|
|
|
private string $cipher; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var string Hash algorithm for key derivation. Recommend sha256, sha384 or sha512. |
34
|
|
|
* @see http://php.net/manual/en/function.hash-algos.php |
35
|
|
|
*/ |
36
|
|
|
private string $kdfAlgorithm = 'sha256'; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @var string HKDF info value for derivation of message authentication key. |
40
|
|
|
*/ |
41
|
|
|
private string $authorizationKeyInfo = 'AuthorizationKey'; |
42
|
|
|
/** |
43
|
|
|
* @var int Derivation iterations count. |
44
|
|
|
* Set as high as possible to hinder dictionary password attacks. |
45
|
|
|
*/ |
46
|
|
|
private int $derivationIterations = 100000; |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param string $cipher The cipher to use for encryption and decryption. |
50
|
|
|
*/ |
51
|
48 |
|
public function __construct(string $cipher = 'AES-128-CBC') |
52
|
|
|
{ |
53
|
48 |
|
if (!extension_loaded('openssl')) { |
54
|
1 |
|
throw new \RuntimeException('Encryption requires the OpenSSL PHP extension'); |
55
|
|
|
} |
56
|
47 |
|
if (!isset(self::ALLOWED_CIPHERS[$cipher][0], self::ALLOWED_CIPHERS[$cipher][1])) { |
57
|
1 |
|
throw new \RuntimeException($cipher . ' is not an allowed cipher'); |
58
|
|
|
} |
59
|
|
|
|
60
|
46 |
|
$this->cipher = $cipher; |
61
|
46 |
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param string $algorithm Hash algorithm for key derivation. Recommend sha256, sha384 or sha512. |
65
|
|
|
* @return self |
66
|
|
|
*/ |
67
|
1 |
|
public function withKdfAlgorithm(string $algorithm): self |
68
|
|
|
{ |
69
|
1 |
|
$new = clone $this; |
70
|
1 |
|
$new->kdfAlgorithm = $algorithm; |
71
|
1 |
|
return $new; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @param string $info HKDF info value for derivation of message authentication key. |
76
|
|
|
* @return self |
77
|
|
|
*/ |
78
|
1 |
|
public function withAuthorizationKeyInfo(string $info): self |
79
|
|
|
{ |
80
|
1 |
|
$new = clone $this; |
81
|
1 |
|
$new->authorizationKeyInfo = $info; |
82
|
1 |
|
return $new; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* @param int $iterations Derivation iterations count. |
87
|
|
|
* Set as high as possible to hinder dictionary password attacks. |
88
|
|
|
* @return self |
89
|
|
|
*/ |
90
|
44 |
|
public function withDerivationIterations(int $iterations): self |
91
|
|
|
{ |
92
|
44 |
|
$new = clone $this; |
93
|
44 |
|
$new->derivationIterations = $iterations; |
94
|
44 |
|
return $new; |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
/** |
98
|
|
|
* Encrypts data using a password. |
99
|
|
|
* |
100
|
|
|
* Derives keys for encryption and authentication from the password using PBKDF2 and a random salt, |
101
|
|
|
* which is deliberately slow to protect against dictionary attacks. Use {@see encryptByKey()} to |
102
|
|
|
* encrypt fast using a cryptographic key rather than a password. Key derivation time is |
103
|
|
|
* determined by {@see $derivationIterations}}, which should be set as high as possible. |
104
|
|
|
* |
105
|
|
|
* The encrypted data includes a keyed message authentication code (MAC) so there is no need |
106
|
|
|
* to hash input or output data. |
107
|
|
|
* |
108
|
|
|
* > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against |
109
|
|
|
* poor-quality or compromised passwords. |
110
|
|
|
* |
111
|
|
|
* @param string $data The data to encrypt. |
112
|
|
|
* @param string $password The password to use for encryption. |
113
|
|
|
* @return string The encrypted data as byte string. |
114
|
|
|
* @throws \RuntimeException On OpenSSL not loaded. |
115
|
|
|
* @throws \Exception On OpenSSL error. |
116
|
|
|
* @see decryptByPassword() |
117
|
|
|
* @see encryptByKey() |
118
|
|
|
*/ |
119
|
4 |
|
public function encryptByPassword(string $data, string $password): string |
120
|
|
|
{ |
121
|
4 |
|
return $this->encrypt($data, true, $password, ''); |
122
|
|
|
} |
123
|
|
|
|
124
|
|
|
/** |
125
|
|
|
* Encrypts data using a cryptographic key. |
126
|
|
|
* |
127
|
|
|
* Derives keys for encryption and authentication from the input key using HKDF and a random salt, |
128
|
|
|
* which is very fast relative to {@see encryptByPassword()}. The input key must be properly |
129
|
|
|
* random — use {@see random_bytes()} to generate keys. |
130
|
|
|
* The encrypted data includes a keyed message authentication code (MAC) so there is no need |
131
|
|
|
* to hash input or output data. |
132
|
|
|
* |
133
|
|
|
* @param string $data The data to encrypt. |
134
|
|
|
* @param string $inputKey The input to use for encryption and authentication. |
135
|
|
|
* @param string $info Context/application specific information, e.g. a user ID |
136
|
|
|
* See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details. |
137
|
|
|
* @return string The encrypted data as byte string. |
138
|
|
|
* @throws \RuntimeException On OpenSSL not loaded. |
139
|
|
|
* @throws \Exception On OpenSSL error. |
140
|
|
|
* @see decryptByKey() |
141
|
|
|
* @see encryptByPassword() |
142
|
|
|
*/ |
143
|
4 |
|
public function encryptByKey(string $data, string $inputKey, string $info = ''): string |
144
|
|
|
{ |
145
|
4 |
|
return $this->encrypt($data, false, $inputKey, $info); |
146
|
|
|
} |
147
|
|
|
|
148
|
|
|
/** |
149
|
|
|
* Verifies and decrypts data encrypted with {@see encryptByPassword()}. |
150
|
|
|
* |
151
|
|
|
* @param string $data The encrypted data to decrypt. |
152
|
|
|
* @param string $password The password to use for decryption. |
153
|
|
|
* @return string The decrypted data. |
154
|
|
|
* @throws \RuntimeException On OpenSSL not loaded. |
155
|
|
|
* @throws \Exception On OpenSSL errors. |
156
|
|
|
* @throws AuthenticationException On authentication failure. |
157
|
|
|
* @see encryptByPassword() |
158
|
|
|
*/ |
159
|
21 |
|
public function decryptByPassword(string $data, string $password): string |
160
|
|
|
{ |
161
|
21 |
|
return $this->decrypt($data, true, $password, ''); |
162
|
|
|
} |
163
|
|
|
|
164
|
|
|
/** |
165
|
|
|
* Verifies and decrypts data encrypted with {@see encryptByKey()}. |
166
|
|
|
* |
167
|
|
|
* @param string $data The encrypted data to decrypt. |
168
|
|
|
* @param string $inputKey The input to use for encryption and authentication. |
169
|
|
|
* @param string $info Context/application specific information, e.g. a user ID |
170
|
|
|
* See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details. |
171
|
|
|
* @return string The decrypted data. |
172
|
|
|
* @throws \RuntimeException On OpenSSL not loaded. |
173
|
|
|
* @throws \Exception On OpenSSL errors. |
174
|
|
|
* @throws AuthenticationException On authentication failure. |
175
|
|
|
* @see encryptByKey() |
176
|
|
|
*/ |
177
|
22 |
|
public function decryptByKey(string $data, string $inputKey, string $info = ''): string |
178
|
|
|
{ |
179
|
22 |
|
return $this->decrypt($data, false, $inputKey, $info); |
180
|
|
|
} |
181
|
|
|
|
182
|
|
|
/** |
183
|
|
|
* Encrypts data. |
184
|
|
|
* |
185
|
|
|
* @param string $data data to be encrypted |
186
|
|
|
* @param bool $passwordBased set true to use password-based key derivation |
187
|
|
|
* @param string $secret the encryption password or key |
188
|
|
|
* @param string $info context/application specific information, e.g. a user ID |
189
|
|
|
* See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details. |
190
|
|
|
* |
191
|
|
|
* @return string the encrypted data as byte string |
192
|
|
|
* @throws \RuntimeException on OpenSSL not loaded |
193
|
|
|
* @throws \Exception on OpenSSL error |
194
|
|
|
* @see decrypt() |
195
|
|
|
*/ |
196
|
8 |
|
private function encrypt(string $data, bool $passwordBased, string $secret, string $info = ''): string |
197
|
|
|
{ |
198
|
8 |
|
[$blockSize, $keySize] = self::ALLOWED_CIPHERS[$this->cipher]; |
199
|
|
|
|
200
|
8 |
|
$keySalt = random_bytes($keySize); |
201
|
8 |
|
if ($passwordBased) { |
202
|
4 |
|
$key = hash_pbkdf2($this->kdfAlgorithm, $secret, $keySalt, $this->derivationIterations, $keySize, true); |
203
|
|
|
} else { |
204
|
4 |
|
$key = hash_hkdf($this->kdfAlgorithm, $secret, $keySize, $info, $keySalt); |
205
|
|
|
} |
206
|
|
|
|
207
|
8 |
|
$iv = random_bytes($blockSize); |
208
|
|
|
|
209
|
8 |
|
$encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv); |
210
|
8 |
|
if ($encrypted === false) { |
211
|
1 |
|
throw new \RuntimeException('OpenSSL failure on encryption: ' . openssl_error_string()); |
212
|
|
|
} |
213
|
|
|
|
214
|
7 |
|
$authKey = hash_hkdf($this->kdfAlgorithm, $key, $keySize, $this->authorizationKeyInfo); |
215
|
7 |
|
$signed = (new Mac())->sign($iv . $encrypted, $authKey); |
|
|
|
|
216
|
|
|
|
217
|
|
|
/* |
218
|
|
|
* Output: [keySalt][MAC][IV][ciphertext] |
219
|
|
|
* - keySalt is KEY_SIZE bytes long |
220
|
|
|
* - MAC: message authentication code, length same as the output of MAC_HASH |
221
|
|
|
* - IV: initialization vector, length $blockSize |
222
|
|
|
*/ |
223
|
7 |
|
return $keySalt . $signed; |
224
|
|
|
} |
225
|
|
|
|
226
|
|
|
/** |
227
|
|
|
* Decrypts data. |
228
|
|
|
* |
229
|
|
|
* @param string $data encrypted data to be decrypted. |
230
|
|
|
* @param bool $passwordBased set true to use password-based key derivation |
231
|
|
|
* @param string $secret the decryption password or key |
232
|
|
|
* @param string $info context/application specific information, @see encrypt() |
233
|
|
|
* |
234
|
|
|
* @return string the decrypted data |
235
|
|
|
* @throws \RuntimeException on OpenSSL not loaded |
236
|
|
|
* @throws \Exception on OpenSSL errors |
237
|
|
|
* @throws AuthenticationException on authentication failure |
238
|
|
|
* @see encrypt() |
239
|
|
|
*/ |
240
|
43 |
|
private function decrypt(string $data, bool $passwordBased, string $secret, string $info): string |
241
|
|
|
{ |
242
|
43 |
|
[$blockSize, $keySize] = self::ALLOWED_CIPHERS[$this->cipher]; |
243
|
|
|
|
244
|
43 |
|
$keySalt = StringHelper::byteSubstring($data, 0, $keySize); |
245
|
43 |
|
if ($passwordBased) { |
246
|
21 |
|
$key = hash_pbkdf2($this->kdfAlgorithm, $secret, $keySalt, $this->derivationIterations, $keySize, true); |
247
|
|
|
} else { |
248
|
22 |
|
$key = hash_hkdf($this->kdfAlgorithm, $secret, $keySize, $info, $keySalt); |
249
|
|
|
} |
250
|
|
|
|
251
|
43 |
|
$authKey = hash_hkdf($this->kdfAlgorithm, $key, $keySize, $this->authorizationKeyInfo); |
252
|
|
|
|
253
|
|
|
try { |
254
|
43 |
|
$data = (new Mac())->getMessage(StringHelper::byteSubstring($data, $keySize), $authKey); |
255
|
3 |
|
} catch (DataIsTamperedException $e) { |
256
|
3 |
|
throw new AuthenticationException('Failed to decrypt data'); |
257
|
|
|
} |
258
|
|
|
|
259
|
40 |
|
$iv = StringHelper::byteSubstring($data, 0, $blockSize); |
260
|
40 |
|
$encrypted = StringHelper::byteSubstring($data, $blockSize); |
261
|
|
|
|
262
|
40 |
|
$decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv); |
263
|
40 |
|
if ($decrypted === false) { |
264
|
1 |
|
throw new \RuntimeException('OpenSSL failure on decryption: ' . openssl_error_string()); |
265
|
|
|
} |
266
|
|
|
|
267
|
39 |
|
return $decrypted; |
|
|
|
|
268
|
|
|
} |
269
|
|
|
} |
270
|
|
|
|