forked from phalcon/cphalcon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypt.zep
622 lines (516 loc) · 14.5 KB
/
crypt.zep
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/*
+------------------------------------------------------------------------+
| Phalcon Framework |
+------------------------------------------------------------------------+
| Copyright (c) 2011-2018 Phalcon Team (http://www.phalconphp.com) |
+------------------------------------------------------------------------+
| This source file is subject to the New BSD License that is bundled |
| with this package in the file LICENSE.txt. |
| |
| If you did not receive a copy of the license and are unable to |
| obtain it through the world-wide-web, please send an email |
| to [email protected] so we can send you a copy immediately. |
+------------------------------------------------------------------------+
| Authors: Andres Gutierrez <[email protected]> |
| Eduar Carvajal <[email protected]> |
+------------------------------------------------------------------------+
*/
namespace Phalcon;
use Phalcon\CryptInterface;
use Phalcon\Crypt\Exception;
use Phalcon\Crypt\Mismatch;
/**
* Phalcon\Crypt
*
* Provides encryption facilities to Phalcon applications.
*
* <code>
* use Phalcon\Crypt;
*
* $crypt = new Crypt();
*
* $crypt->setCipher('aes-256-ctr');
*
* $key = "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3";
* $text = "The message to be encrypted";
*
* $encrypted = $crypt->encrypt($text, $key);
*
* echo $crypt->decrypt($encrypted, $key);
* </code>
*/
class Crypt implements CryptInterface
{
protected _key;
protected _padding = 0;
protected _cipher = "aes-256-cfb";
/**
* Available cipher methods.
* @var array
*/
protected availableCiphers;
/**
* The cipher iv length.
* @var int
*/
protected ivLength = 16;
/**
* The name of hashing algorithm.
* @var string
*/
protected hashAlgo = "sha256";
/**
* Whether calculating message digest enabled or not.
* NOTE: This feature will be enabled by default in Phalcon 4.0.0
* @var bool
*/
protected useSigning = false;
const PADDING_DEFAULT = 0;
const PADDING_ANSI_X_923 = 1;
const PADDING_PKCS7 = 2;
const PADDING_ISO_10126 = 3;
const PADDING_ISO_IEC_7816_4 = 4;
const PADDING_ZERO = 5;
const PADDING_SPACE = 6;
/**
* Phalcon\Crypt constructor.
*/
public function __construct(string! cipher = "aes-256-cfb", boolean useSigning = false)
{
this->initializeAvailableCiphers();
this->setCipher(cipher);
this->useSigning(useSigning);
}
/**
* Changes the padding scheme used.
*/
public function setPadding(int! scheme) -> <CryptInterface>
{
let this->_padding = scheme;
return this;
}
/**
* Sets the cipher algorithm for data encryption and decryption.
*
* The `aes-256-gcm' is the preferable cipher, but it is not usable
* until the openssl library is upgraded, which is available in PHP 7.1.
*
* The `aes-256-ctr' is arguably the best choice for cipher
* algorithm for current openssl library version.
*/
public function setCipher(string! cipher) -> <Crypt>
{
this->assertCipherIsAvailable(cipher);
let this->ivLength = this->getIvLength(cipher),
this->_cipher = cipher;
return this;
}
/**
* Returns the current cipher
*/
public function getCipher() -> string
{
return this->_cipher;
}
/**
* Sets the encryption key.
*
* The `$key' should have been previously generated in a cryptographically safe way.
*
* Bad key:
* "le password"
*
* Better (but still unsafe):
* "#1dj8$=dp?.ak//j1V$~%*0X"
*
* Good key:
* "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
*
* @see \Phalcon\Security\Random
*/
public function setKey(string! key) -> <Crypt>
{
let this->_key = key;
return this;
}
/**
* Returns the encryption key
*/
public function getKey() -> string
{
return this->_key;
}
/**
* Set the name of hashing algorithm.
*
* @throws \Phalcon\Crypt\Exception
*/
public function setHashAlgo(string! hashAlgo) -> <Crypt>
{
this->assertHashAlgorithmAvailable(hashAlgo);
let this->hashAlgo = hashAlgo;
return this;
}
/**
* Get the name of hashing algorithm.
*/
public function getHashAlgo() -> string
{
return this->hashAlgo;
}
/**
* Sets if the calculating message digest must used.
*
* NOTE: This feature will be enabled by default in Phalcon 4.0.0
*/
public function useSigning(boolean useSigning) -> <Crypt>
{
let this->useSigning = useSigning;
return this;
}
/**
* Pads texts before encryption.
*
* @link http://www.di-mgt.com.au/cryptopad.html
*/
protected function _cryptPadText(string text, string! mode, int! blockSize, int! paddingType)
{
int i;
var paddingSize = 0, padding = null;
if mode == "cbc" || mode == "ecb" {
let paddingSize = blockSize - (strlen(text) % blockSize);
if paddingSize >= 256 {
throw new Exception("Block size is bigger than 256");
}
switch paddingType {
case self::PADDING_ANSI_X_923:
let padding = str_repeat(chr(0), paddingSize - 1) . chr(paddingSize);
break;
case self::PADDING_PKCS7:
let padding = str_repeat(chr(paddingSize), paddingSize);
break;
case self::PADDING_ISO_10126:
let padding = "";
for i in range(0, paddingSize - 2) {
let padding .= chr(rand());
}
let padding .= chr(paddingSize);
break;
case self::PADDING_ISO_IEC_7816_4:
let padding = chr(0x80) . str_repeat(chr(0), paddingSize - 1);
break;
case self::PADDING_ZERO:
let padding = str_repeat(chr(0), paddingSize);
break;
case self::PADDING_SPACE:
let padding = str_repeat(" ", paddingSize);
break;
default:
let paddingSize = 0;
break;
}
}
if !paddingSize {
return text;
}
if paddingSize > blockSize {
throw new Exception("Invalid padding size");
}
return text . substr(padding, 0, paddingSize);
}
/**
* Removes a padding from a text.
*
* If the function detects that the text was not padded, it will return it unmodified.
*
* @param string text Message to be unpadded
* @param string mode Encryption mode; unpadding is applied only in CBC or ECB mode
* @param int blockSize Cipher block size
* @param int paddingType Padding scheme
*/
protected function _cryptUnpadText(string text, string! mode, int! blockSize, int! paddingType)
{
var padding, last;
long length;
int i, paddingSize = 0, ord;
let length = strlen(text);
if length > 0 && (length % blockSize == 0) && (mode == "cbc" || mode == "ecb") {
switch paddingType {
case self::PADDING_ANSI_X_923:
let last = substr(text, length - 1, 1);
let ord = (int) ord(last);
if ord <= blockSize {
let paddingSize = ord;
let padding = str_repeat(chr(0), paddingSize - 1) . last;
if substr(text, length - paddingSize) != padding {
let paddingSize = 0;
}
}
break;
case self::PADDING_PKCS7:
let last = substr(text, length - 1, 1);
let ord = (int) ord(last);
if ord <= blockSize {
let paddingSize = ord;
let padding = str_repeat(chr(paddingSize), paddingSize);
if substr(text, length - paddingSize) != padding {
let paddingSize = 0;
}
}
break;
case self::PADDING_ISO_10126:
let last = substr(text, length - 1, 1);
let paddingSize = (int) ord(last);
break;
case self::PADDING_ISO_IEC_7816_4:
let i = length - 1;
while i > 0 && text[i] == 0x00 && paddingSize < blockSize {
let paddingSize++, i--;
}
if text[i] == 0x80 {
let paddingSize++;
} else {
let paddingSize = 0;
}
break;
case self::PADDING_ZERO:
let i = length - 1;
while i >= 0 && text[i] == 0x00 && paddingSize <= blockSize {
let paddingSize++, i--;
}
break;
case self::PADDING_SPACE:
let i = length - 1;
while i >= 0 && text[i] == 0x20 && paddingSize <= blockSize {
let paddingSize++, i--;
}
break;
default:
break;
}
if paddingSize && paddingSize <= blockSize {
if paddingSize < length {
return substr(text, 0, length - paddingSize);
}
return "";
} else {
let paddingSize = 0;
}
}
if !paddingSize {
return text;
}
}
/**
* Encrypts a text.
*
* <code>
* $encrypted = $crypt->encrypt(
* "Top secret",
* "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
* );
* </code>
*/
public function encrypt(string! text, string! key = null) -> string
{
var encryptKey, ivLength, iv, cipher, mode, blockSize, paddingType, padded, encrypted;
if likely empty key {
let encryptKey = this->_key;
} else {
let encryptKey = key;
}
if empty encryptKey {
throw new Exception("Encryption key cannot be empty");
}
let cipher = this->_cipher;
let mode = strtolower(substr(cipher, strrpos(cipher, "-") - strlen(cipher)));
this->assertCipherIsAvailable(cipher);
let ivLength = this->ivLength;
if likely ivLength > 0 {
let blockSize = ivLength;
} else {
let blockSize = this->getIvLength(str_ireplace("-" . mode, "", cipher));
}
let iv = openssl_random_pseudo_bytes(ivLength);
let paddingType = this->_padding;
if paddingType != 0 && (mode == "cbc" || mode == "ecb") {
let padded = this->_cryptPadText(text, mode, blockSize, paddingType);
} else {
let padded = text;
}
let encrypted = openssl_encrypt(padded, cipher, encryptKey, OPENSSL_RAW_DATA, iv);
if this->useSigning {
var digest, hashAlgo;
let hashAlgo = this->getHashAlgo();
let digest = hash_hmac(hashAlgo, padded, encryptKey, true);
return iv . digest . encrypted;
}
return iv . encrypted;
}
/**
* Decrypts an encrypted text.
*
* <code>
* $encrypted = $crypt->decrypt(
* $encrypted,
* "T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
* );
* </code>
*
* @throws \Phalcon\Crypt\Mismatch
*/
public function decrypt(string! text, string! key = null) -> string
{
var decryptKey, ivLength, cipher, mode, blockSize, decrypted,
ciphertext, hashAlgo, hashLength, iv, hash;
if likely empty key {
let decryptKey = this->_key;
} else {
let decryptKey = key;
}
if empty decryptKey {
throw new Exception("Decryption key cannot be empty");
}
let cipher = this->_cipher;
let mode = strtolower(substr(cipher, strrpos(cipher, "-") - strlen(cipher)));
this->assertCipherIsAvailable(cipher);
let ivLength = this->ivLength;
if likely ivLength > 0 {
let blockSize = ivLength;
} else {
let blockSize = this->getIvLength(str_ireplace("-" . mode, "", cipher));
}
let iv = mb_substr(text, 0, ivLength, "8bit");
if this->useSigning {
let hashAlgo = this->getHashAlgo();
let hashLength = strlen(hash(hashAlgo, "", true));
let hash = mb_substr(text, ivLength, hashLength, "8bit");
let ciphertext = mb_substr(text, ivLength + hashLength, null, "8bit");
let decrypted = openssl_decrypt(ciphertext, cipher, decryptKey, OPENSSL_RAW_DATA, iv);
if mode == "cbc" || mode == "ecb" {
let decrypted = this->_cryptUnpadText(decrypted, mode, blockSize, this->_padding);
}
/**
* Checkson the decrypted's message digest using the HMAC method.
*/
if hash_hmac(hashAlgo, decrypted, decryptKey, true) !== hash {
throw new Mismatch("Hash does not match.");
}
return decrypted;
}
let ciphertext = mb_substr(text, ivLength, null, "8bit");
let decrypted = openssl_decrypt(ciphertext, cipher, decryptKey, OPENSSL_RAW_DATA, iv);
if mode == "cbc" || mode == "ecb" {
let decrypted = this->_cryptUnpadText(decrypted, mode, blockSize, this->_padding);
}
return decrypted;
}
/**
* Encrypts a text returning the result as a base64 string.
*/
public function encryptBase64(string! text, key = null, boolean! safe = false) -> string
{
if safe == true {
return rtrim(strtr(base64_encode(this->encrypt(text, key)), "+/", "-_"), "=");
}
return base64_encode(this->encrypt(text, key));
}
/**
* Decrypt a text that is coded as a base64 string.
*
* @throws \Phalcon\Crypt\Mismatch
*/
public function decryptBase64(string! text, key = null, boolean! safe = false) -> string
{
if safe == true {
return this->decrypt(base64_decode(strtr(text, "-_", "+/") . substr("===", (strlen(text) + 3) % 4)), key);
}
return this->decrypt(base64_decode(text), key);
}
/**
* Returns a list of available ciphers.
*/
public function getAvailableCiphers() -> array
{
var availableCiphers;
let availableCiphers = this->availableCiphers;
if unlikely typeof availableCiphers !== "array" {
this->initializeAvailableCiphers();
let availableCiphers = this->availableCiphers;
}
return availableCiphers;
}
/**
* Return a list of registered hashing algorithms suitable for hash_hmac.
*/
public function getAvailableHashAlgos() -> array
{
var algos;
if likely function_exists("hash_hmac_algos") {
let algos = hash_hmac_algos();
} else {
let algos = hash_algos();
}
return algos;
}
/**
* Assert the cipher is available.
*
* @throws \Phalcon\Crypt\Exception
*/
protected function assertCipherIsAvailable(string! cipher) -> void
{
var availableCiphers;
let availableCiphers = this->getAvailableCiphers();
if !in_array(cipher, availableCiphers) {
throw new Exception(
sprintf(
"The cipher algorithm \"%s\" is not supported on this system.",
cipher
)
);
}
}
/**
* Assert the hash algorithm is available.
*
* @throws \Phalcon\Crypt\Exception
*/
protected function assertHashAlgorithmAvailable(string! hashAlgo) -> void
{
var availableAlgorithms;
let availableAlgorithms = this->getAvailableHashAlgos();
if !in_array(hashAlgo, availableAlgorithms) {
throw new Exception(
sprintf(
"The hash algorithm \"%s\" is not supported on this system.",
hashAlgo
)
);
}
}
/**
* Initialize available cipher algorithms.
*
* @throws \Phalcon\Crypt\Exception
*/
protected function getIvLength(string! cipher) -> int
{
if !function_exists("openssl_cipher_iv_length") {
throw new Exception("openssl extension is required");
}
return openssl_cipher_iv_length(cipher);
}
/**
* Initialize available cipher algorithms.
*
* @throws \Phalcon\Crypt\Exception
*/
protected function initializeAvailableCiphers() -> void
{
if !function_exists("openssl_get_cipher_methods") {
throw new Exception("openssl extension is required");
}
let this->availableCiphers = openssl_get_cipher_methods(true);
}
}