|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace diecoding\flysystem\traits; |
|
4
|
|
|
|
|
5
|
|
|
use Yii; |
|
6
|
|
|
use yii\base\InvalidConfigException; |
|
7
|
|
|
use yii\helpers\StringHelper; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Trait EncrypterTrait for Model |
|
11
|
|
|
* |
|
12
|
|
|
* @link https://sugengsulistiyawan.my.id/ |
|
13
|
|
|
* @author Sugeng Sulistiyawan <[email protected]> |
|
14
|
|
|
* @copyright Copyright (c) 2023 |
|
15
|
|
|
*/ |
|
16
|
|
|
trait EncrypterTrait |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @var string |
|
20
|
|
|
*/ |
|
21
|
|
|
private $_passphrase; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Init Encrypter |
|
25
|
|
|
* |
|
26
|
|
|
* @param string $passphrase |
|
27
|
|
|
* |
|
28
|
|
|
* @return void |
|
29
|
|
|
* @throws InvalidConfigException |
|
30
|
|
|
*/ |
|
31
|
|
|
public function initEncrypter($passphrase) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->normalizePassphrase($passphrase); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Encrypts a string. |
|
38
|
|
|
* |
|
39
|
|
|
* @param string $string the string to encrypt |
|
40
|
|
|
* @return string the encrypted string |
|
41
|
|
|
*/ |
|
42
|
|
|
public function encrypt($string) |
|
43
|
|
|
{ |
|
44
|
|
|
$encrypted = Yii::$app->getSecurity()->encryptByPassword($string, $this->_passphrase); |
|
45
|
|
|
|
|
46
|
|
|
return StringHelper::base64UrlEncode($encrypted); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Decrypts a string. |
|
51
|
|
|
* False is returned in case it was not possible to decrypt it. |
|
52
|
|
|
* |
|
53
|
|
|
* @param string $string the string to decrypt |
|
54
|
|
|
* @return string|bool the decrypted string or false on authentication failure |
|
55
|
|
|
*/ |
|
56
|
|
|
public function decrypt($string) |
|
57
|
|
|
{ |
|
58
|
|
|
$encrypted = StringHelper::base64UrlDecode($string); |
|
59
|
|
|
$decrypted = Yii::$app->getSecurity()->decryptByPassword($encrypted, $this->_passphrase); |
|
60
|
|
|
|
|
61
|
|
|
return $decrypted; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* @param string $passphrase |
|
66
|
|
|
* @param int $minPassphraseLength |
|
67
|
|
|
* |
|
68
|
|
|
* @return void |
|
69
|
|
|
* @throws InvalidConfigException |
|
70
|
|
|
*/ |
|
71
|
|
|
private function normalizePassphrase($passphrase) |
|
72
|
|
|
{ |
|
73
|
|
|
$this->_passphrase = $passphrase; |
|
74
|
|
|
if (empty($this->_passphrase)) { |
|
75
|
|
|
throw new InvalidConfigException('The "passphrase" property must be set.'); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
$minPassphraseLength = 32; |
|
79
|
|
|
$passphraseLength = strlen($this->_passphrase); |
|
80
|
|
|
if ($passphraseLength < $minPassphraseLength) { |
|
81
|
|
|
$this->_passphrase = str_repeat($this->_passphrase, (int) ceil($minPassphraseLength / $passphraseLength)); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|