-
Notifications
You must be signed in to change notification settings - Fork 6
/
Secret.php
377 lines (338 loc) · 11 KB
/
Secret.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php
/**
* Copyright (c) 2014, Andrey Andreev <narf@devilix.net>
* All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* Simple Encryption for PHP
*
* A simple symmetric encryption library, currently providing
* AES-256-CTR-HMAC-SHA256 as the only available encryption method.
*
* @package SimpleEncryption
* @author Andrey Andreev <narf@devilix.net>
* @copyright Copyright (c) 2014, Andrey Andreev <narf@devilix.net>
* @license http://opensource.org/licenses/ISC ISC License (ISC)
* @link https://github.com/narfbg/SimpleEncryption
*/
namespace Narf\SimpleEncryption;
class Secret {
const VERSION = '0.3.0';
// These are passed to the constructor to specify the
// input data type. In the future, when the default
// encryption scheme changes, the ENCRYPTED value will
// change as well, and another constant will be added
// for (decryption) backwards compatibility.
const PLAINTEXT = 0;
const ENCRYPTED = 1;
// Data placeholders
private $inputText, $inputType, $masterKey;
/**
* __construct()
*
* @param string $inputText Input text
* @param int $inputType Input type
* @param string $masterKey Master key
*/
public function __construct($inputText, $masterKey = null, $inputType = null)
{
// Validate input type
if (isset($inputType))
{
if ($inputType === self::ENCRYPTED && ! isset($masterKey))
{
throw new \InvalidArgumentException('Input type is Secret::ENCRYPTED, but there is no key.');
}
elseif ($inputType !== self::PLAINTEXT && $inputType !== self::ENCRYPTED)
{
throw new \InvalidArgumentException('Input type must be Secret::PLAINTEXT or Secret::ENCRYPTED');
}
$this->inputType = $inputType;
}
// Validate key (length) if it exists, and guess the input type if necessary
if (isset($masterKey))
{
if ( ! \preg_match('/^[0-9a-f]{64}$/i', $masterKey))
{
throw new \InvalidArgumentException('Invalid key format, please use getKey() to create your own keys.');
}
$this->masterKey = \pack('H*', $masterKey);
isset($this->inputType) OR $this->inputType = self::ENCRYPTED;
}
elseif ( ! isset($this->inputType)) $this->inputType = self::PLAINTEXT;
$this->inputText = $inputText;
}
/**
* getCipherText()
*
* Does the following:
*
* - If the input was an encrypted message, calls getPlainText() to decrypt it
* - If the input was a plain-text message and no master key is set, the key is generated
* - Generates a random IV
* - Derives a cipher and a HMAC key from the master key, via HKDF
* - Encrypts the plainText message and prepends the IV to it
* - Prepends a HMAC-SHA256 message to the cipher text encodes it using Base64
*
* The result is not cached and the whole process is repeated for each call,
* resulting in different IV and cipher text every time.
*
* @return string Cipher text
*/
public function getCipherText()
{
if (isset($this->masterKey)) $iv = self::getRandomBytes(16, true);
else list($this->masterKey, $iv) = \str_split(self::getRandomBytes(48, true), 32);
list($cipherKey, $hmacKey) = \str_split(self::hkdf($this->masterKey, 'sha512', 64, 'aes-256-ctr-hmac-sha256'), 32);
$data = ($this->inputType === self::PLAINTEXT)
? $this->inputText
: $this->getPlainText();
if (($data = \openssl_encrypt($data, 'aes-256-ctr', $cipherKey, 1, $iv)) === false)
{
// @codeCoverageIgnoreStart
throw new \RuntimeException('Error during encryption procedure.');
// @codeCoverageIgnoreEnd
}
return \base64_encode(\hash_hmac('sha256', $iv.$data, $hmacKey, true).$iv.$data);
}
/**
* getPlainText()
*
* Does the following:
*
* - If the input was a plain-text message, simply returns it
* - The cipher and HMAC keys are derived from the master key
* - Validates and strips Base64 encoding
* - Calls authenticate(), which strips the Base64 encoding and HMAC message
* - Separates the IV and decrypts the message
*
* The result is cached to speed-up subsequent calls.
*
* @return string Plain-text message
*/
public function getPlainText()
{
if ($this->inputType === self::PLAINTEXT)
{
return $this->inputText;
}
list($cipherKey, $hmacKey) = \str_split(self::hkdf($this->masterKey, 'sha512', 64, 'aes-256-ctr-hmac-sha256'), 32);
// authenticate() receives $data by reference
$data = $this->inputText;
$this->authenticate($data, $hmacKey);
$data = \openssl_decrypt(
self::substr($data, 16),
'aes-256-ctr',
$cipherKey,
1,
self::substr($data, 0, 16)
);
if ($data === false)
{
// @codeCoverageIgnoreStart
throw new \RuntimeException('Error during decryption procedure.');
// @codeCoverageIgnoreEnd
}
return $data;
}
/**
* getKey()
*
* Generates a key, unless already set, and then returns it.
*
* @return string Key
*/
public function getKey()
{
isset($this->masterKey) OR $this->masterKey = self::getRandomBytes(32, true);
return \bin2hex($this->masterKey);
}
/**
* getRandomBytes()
*
* Reads the specified amount of data from the system's PRNG.
*
* @param int $length Desired output length
* @return string A pseudo-random stream of bytes
*/
public static function getRandomBytes($length, $rawOutput = false)
{
if ( ! is_int($length) OR $length < 1)
{
throw new \InvalidArgumentException('Length must be an integer larger than 0.');
}
// @codeCoverageIgnoreStart
if (\function_exists('openssl_random_pseudo_bytes'))
{
$cryptoStrong = null;
if (($output = \openssl_random_pseudo_bytes($length, $cryptoStrong)) !== false && $cryptoStrong)
{
return ($rawOutput) ? $output : \bin2hex($output);
}
}
if (\defined('MCRYPT_DEV_URANDOM'))
{
if (($output = \mcrypt_create_iv($length, MCRYPT_DEV_URANDOM)) !== false)
{
return ($rawOutput) ? $output : \bin2hex($output);
}
}
if (\is_readable('/dev/urandom') && ($fp = \fopen('/dev/urandom', 'rb')) !== false)
{
\stream_set_chunk_size($fp, $length);
$output = \fread($fp, $length);
\fclose($fp);
if ($output !== false)
{
return ($rawOutput) ? $output : \bin2hex($output);
}
}
throw new \RuntimeException('No reliable PRNG source is available on the system.');
// @codeCoverageIgnoreEnd
}
/**
* hkdf()
*
* An RFC5869-compliant HMAC Key Derivation Function implementation.
*
* @link https://tools.ietf.org/rfc/rfc5869.txt
* @param string $key Input key material
* @param string $digest Hashing algorithm
* @param int $length Desired output length
* @param string $info Context/application-specific info
* @param string $salt Salt
* @return string A pseudo-random stream of bytes
*/
public static function hkdf($key, $digest, $length = null, $info = '', $salt = null)
{
static $digests;
isset($digests) OR $digests = array('sha512' => 64);
if ( ! isset($digests[$digest]))
{
if (\in_array($digest, \hash_algos(), true)) $digests[$digest] = self::strlen(\hash($digest, '', true));
else throw new \InvalidArgumentException('Unknown HKDF algorithm: '.$digest);
}
if ( ! isset($length))
{
$length = $digests[$digest];
}
elseif ( ! \is_int($length) OR $length < 1 OR $length > (255 * $digests[$digest]))
{
throw new \InvalidArgumentException('HKDF output length for '.$digest.' must be an integer between 1 and '.(255 * $digests[$digest]));
}
self::strlen($salt) OR $salt = \str_repeat("\x0", $digests[$digest]);
$prk = \hash_hmac($digest, $key, $salt, true);
$key = '';
for ($keyBlock = '', $blockIndex = 1; self::strlen($key) < $length; $blockIndex++)
{
$keyBlock = \hash_hmac($digest, $keyBlock.$info.\chr($blockIndex), $prk, true);
$key .= $keyBlock;
}
return self::substr($key, 0, $length);
}
/**
* authenticate()
*
* Validates and strips Base64 encoding, then separates the HMAC message from
* the cipher text and verifies them in a way that prevents timing attacks.
*
* @param string &$cipherText Cipher text
* @param string $hmacKey HMAC key
* @return void
*/
private function authenticate(&$cipherText, $hmacKey)
{
if (($length = self::strlen($cipherText)) <= 32 OR ($length % 4) !== 0)
{
throw new \RuntimeException('Authentication failed: Invalid length');
}
elseif (($cipherText = \base64_decode($cipherText, true)) === false)
{
// @codeCoverageIgnoreStart
throw new \RuntimeException('Authentication failed: Input data is not a valid Base64 string.');
// @codeCoverageIgnoreEnd
}
$hmacRecv = self::substr($cipherText, 0, 32);
$cipherText = self::substr($cipherText, 32);
$hmacCalc = \hash_hmac('sha256', $cipherText, $hmacKey, true);
/**
* Double HMAC verification
*
* Protects against timing side-channel attacks by randomizing the
* attacker's guess input instead of trying to directly compare in
* a constant time fashion. The latter is apparently not always
* possible due to run-time or compile-time optimizations.
*
* Reference: https://www.isecpartners.com/blog/2011/february/double-hmac-verification.aspx
*
* A note on MD5 usage here:
*
* As explained, the goal is simply to change the strings being
* compared, so we don't need a strong algorithm, just a fast one.
*/
if (\hash_hmac('md5', $hmacRecv, $hmacKey) !== \hash_hmac('md5', $hmacCalc, $hmacKey))
{
throw new \RuntimeException('Authentication failed: HMAC mismatch');
}
}
/**
* __sleep()
*
* Prevents serialization to avoid accidental data leaks.
*/
public final function __sleep()
{
throw new \RuntimeException('Serialization is not allowed!');
return array();
}
/**
* strlen()
*
* We use this to make sure that we're counting bytes
* instead of multibyte characters.
*
* @param string $string Input string
* @return int
*/
private static function strlen($string)
{
return (\defined('MB_OVERLOAD_STRING'))
? \mb_strlen($string, '8bit')
: \strlen($string);
}
/**
* substr()
*
* We use this to make sure that we're cutting at byte
* counts instead of multibyte character boundaries.
*
* @param string $string Input string
* @param int $start Starting byte index
* @param int $length Output string length
* @return string Output string
*/
private static function substr($string, $start, $length = null)
{
if (\defined('MB_OVERLOAD_STRING'))
{
return \mb_substr($string, $start, $length, '8bit');
}
// Unlike mb_substr(), substr() returns an empty string
// if we pass null as the $length value.
return isset($length)
? \substr($string, $start, $length)
: \substr($string, $start);
}
}