Created
September 18, 2019 19:26
Encrypt data after changing the APP_KEY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use DB; | |
use Illuminate\Encryption\Encrypter; | |
use Illuminate\Support\Str; | |
use Illuminate\Console\Command; | |
class ReEncryptData extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'resonate:re-encrypt'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'After updating the APP_KEY we need to re-encrypt all data that was encrypted and stored in the app.'; | |
/** | |
* Create a new command instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
/** | |
* Execute the console command. | |
* | |
* @return mixed | |
*/ | |
public function handle() | |
{ | |
$oldValues = []; | |
$newValues = []; | |
$oldKey = $this->ask('What is the old APP_KEY?'); | |
$oldKey = $this->stripBase64Prefix($oldKey); | |
$newKey = $this->ask('What is the new APP_KEY? (press enter for...)', env('APP_KEY')); | |
$newKey = $this->stripBase64Prefix($newKey); | |
do { | |
$table = $this->ask('What is the name of the table?'); | |
$column = $this->ask('What is the name of the encrypted column?'); | |
$previousEncrypter = new Encrypter($oldKey, config('app.cipher')); | |
$newEncrypter = new Encrypter($newKey, config('app.cipher')); | |
foreach (DB::table($table)->get() as $row) { | |
$oldValues[$row->id] = $row->{$column}; | |
$decryptedValue = $previousEncrypter->decrypt($row->{$column}); | |
$encryptedValue = $newEncrypter->encrypt($decryptedValue); | |
$newValues[$row->id] = $encryptedValue; | |
DB::table($table) | |
->where('id', $row->id) | |
->update([$column => $encryptedValue]); | |
} | |
$this->info("Here are the old values encrypted with the old key:"); | |
$this->info(json_encode($oldValues)); | |
$this->info("Here are the new values encrypted with the new key:"); | |
$this->info(json_encode($newValues)); | |
} while ($this->confirm('Do you have more columns to encrypt?')); | |
} | |
/** | |
* Strip "base64:" off the front of the APP_KEY | |
*/ | |
public function stripBase64Prefix($key) | |
{ | |
if (Str::startsWith($key, 'base64:')) { | |
$key = base64_decode(substr($key, 7)); | |
} | |
return $key; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment