-
Notifications
You must be signed in to change notification settings - Fork 30
/
EncryptionServiceProvider.php
executable file
·87 lines (76 loc) · 2.09 KB
/
EncryptionServiceProvider.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
<?php
namespace Illuminate\Encryption;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Laravel\SerializableClosure\SerializableClosure;
class EncryptionServiceProvider extends ServiceProvider
{
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->registerEncrypter();
$this->registerSerializableClosureSecurityKey();
}
/**
* Register the encrypter.
*
* @return void
*/
protected function registerEncrypter()
{
$this->app->singleton('encrypter', function ($app) {
$config = $app->make('config')->get('app');
return (new Encrypter($this->parseKey($config), $config['cipher']))
->previousKeys(array_map(
fn ($key) => $this->parseKey(['key' => $key]),
$config['previous_keys'] ?? []
));
});
}
/**
* Configure Serializable Closure signing for security.
*
* @return void
*/
protected function registerSerializableClosureSecurityKey()
{
$config = $this->app->make('config')->get('app');
if (! class_exists(SerializableClosure::class) || empty($config['key'])) {
return;
}
SerializableClosure::setSecretKey($this->parseKey($config));
}
/**
* Parse the encryption key.
*
* @param array $config
* @return string
*/
protected function parseKey(array $config)
{
if (Str::startsWith($key = $this->key($config), $prefix = 'base64:')) {
$key = base64_decode(Str::after($key, $prefix));
}
return $key;
}
/**
* Extract the encryption key from the given configuration.
*
* @param array $config
* @return string
*
* @throws \Illuminate\Encryption\MissingAppKeyException
*/
protected function key(array $config)
{
return tap($config['key'], function ($key) {
if (empty($key)) {
throw new MissingAppKeyException;
}
});
}
}