forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGenerateKey.php
More file actions
206 lines (167 loc) · 6.02 KB
/
GenerateKey.php
File metadata and controls
206 lines (167 loc) · 6.02 KB
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
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Commands\Encryption;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Config\DotEnv;
use CodeIgniter\Encryption\Encryption;
use Config\Paths;
/**
* Generates a new encryption key.
*/
class GenerateKey extends BaseCommand
{
/**
* The Command's group.
*
* @var string
*/
protected $group = 'Encryption';
/**
* The Command's name.
*
* @var string
*/
protected $name = 'key:generate';
/**
* The Command's usage.
*
* @var string
*/
protected $usage = 'key:generate [options]';
/**
* The Command's short description.
*
* @var string
*/
protected $description = 'Generates a new encryption key and writes it in an `.env` file.';
/**
* The command's options
*
* @var array<string, string>
*/
protected $options = [
'--force' => 'Force overwrite existing key in `.env` file.',
'--length' => 'The length of the random string that should be returned in bytes. Defaults to 32.',
'--prefix' => 'Prefix to prepend to encoded key (either hex2bin or base64). Defaults to hex2bin.',
'--show' => 'Shows the generated key in the terminal instead of storing in the `.env` file.',
];
/**
* Actually execute the command.
*/
public function run(array $params)
{
$prefix = $params['prefix'] ?? CLI::getOption('prefix');
if (in_array($prefix, [null, true], true)) {
$prefix = 'hex2bin';
} elseif (! in_array($prefix, ['hex2bin', 'base64'], true)) {
$prefix = CLI::prompt('Please provide a valid prefix to use.', ['hex2bin', 'base64'], 'required'); // @codeCoverageIgnore
}
$length = $params['length'] ?? CLI::getOption('length');
if (in_array($length, [null, true], true)) {
$length = 32;
}
$encodedKey = $this->generateRandomKey($prefix, $length);
if (array_key_exists('show', $params) || (bool) CLI::getOption('show')) {
CLI::write($encodedKey, 'yellow');
CLI::newLine();
return;
}
if (! $this->setNewEncryptionKey($encodedKey, $params)) {
CLI::write('Error in setting new encryption key to .env file.', 'light_gray', 'red');
CLI::newLine();
return;
}
// force DotEnv to reload the new env vars
putenv('encryption.key');
unset($_ENV['encryption.key'], $_SERVER['encryption.key']);
$dotenv = new DotEnv((new Paths())->envDirectory ?? ROOTPATH); // @phpstan-ignore nullCoalesce.property
$dotenv->load();
CLI::write('Application\'s new encryption key was successfully set.', 'green');
CLI::newLine();
}
/**
* Generates a key and encodes it.
*/
protected function generateRandomKey(string $prefix, int $length): string
{
$key = Encryption::createKey($length);
if ($prefix === 'hex2bin') {
return 'hex2bin:' . bin2hex($key);
}
return 'base64:' . base64_encode($key);
}
/**
* Sets the new encryption key in your .env file.
*
* @param array<int|string, string|null> $params
*/
protected function setNewEncryptionKey(string $key, array $params): bool
{
$currentKey = env('encryption.key', '');
if ($currentKey !== '' && ! $this->confirmOverwrite($params)) {
// Not yet testable since it requires keyboard input
return false; // @codeCoverageIgnore
}
return $this->writeNewEncryptionKeyToFile($currentKey, $key);
}
/**
* Checks whether to overwrite existing encryption key.
*
* @param array<int|string, string|null> $params
*/
protected function confirmOverwrite(array $params): bool
{
return (array_key_exists('force', $params) || CLI::getOption('force')) || CLI::prompt('Overwrite existing key?', ['n', 'y']) === 'y';
}
/**
* Writes the new encryption key to .env file.
*/
protected function writeNewEncryptionKeyToFile(string $oldKey, string $newKey): bool
{
$baseEnv = ROOTPATH . 'env';
$envFile = ((new Paths())->envDirectory ?? ROOTPATH) . '.env'; // @phpstan-ignore nullCoalesce.property
if (! is_file($envFile)) {
if (! is_file($baseEnv)) {
CLI::write('Both default shipped `env` file and custom `.env` are missing.', 'yellow');
CLI::write('Here\'s your new key instead: ' . CLI::color($newKey, 'yellow'));
CLI::newLine();
return false;
}
copy($baseEnv, $envFile);
}
$oldFileContents = (string) file_get_contents($envFile);
$replacementKey = "\nencryption.key = {$newKey}";
if (! str_contains($oldFileContents, 'encryption.key')) {
return file_put_contents($envFile, $replacementKey, FILE_APPEND) !== false;
}
$newFileContents = preg_replace($this->keyPattern($oldKey), $replacementKey, $oldFileContents);
if ($newFileContents === $oldFileContents) {
$newFileContents = preg_replace(
'/^[#\s]*encryption.key[=\s]*(?:hex2bin\:[a-f0-9]{64}|base64\:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?)$/m',
$replacementKey,
$oldFileContents,
);
}
return file_put_contents($envFile, $newFileContents) !== false;
}
/**
* Get the regex of the current encryption key.
*/
protected function keyPattern(string $oldKey): string
{
$escaped = preg_quote($oldKey, '/');
if ($escaped !== '') {
$escaped = "[{$escaped}]*";
}
return "/^[#\\s]*encryption.key[=\\s]*{$escaped}$/m";
}
}