Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Re-encryption after APP_KEY rotation
<?php
namespace App\Providers;
use App\Encrypter;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('encrypter', function($app){
$config = $app->make('config')->get('app');
if (Str::startsWith($key = $config['key'], 'base64:')) {
$key = base64_decode(substr($key, 7));
}
return new Encrypter($key, $config['cipher']);
});
}
}
<?php
namespace App;
use Illuminate\Support\Str;
class Encrypter extends \Illuminate\Encryption\Encrypter
{
/**
* Decrypt the given value.
*
* @param string $payload
* @param bool $unserialize
* @return mixed
*
* @throws \Illuminate\Contracts\Encryption\DecryptException
*/
public function decrypt($payload, $unserialize = true)
{
try{
return parent::decrypt($payload, $unserialize);
}catch(\Throwable $e){
$currentKey = $this->key;
$this->key = Str::startsWith(config('app.old_key'), 'base64:')
? base64_decode(substr(config('app.old_key'), 7))
: config('app.old_key');
return tap(parent::decrypt($payload, $unserialize), function () use ($currentKey) {
$this->key = $currentKey;
});
}
}
}
@anouarabdsslm

This comment has been minimized.

Copy link

@anouarabdsslm anouarabdsslm commented May 24, 2020

thanks you for this 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.