Skip to content

Instantly share code, notes, and snippets.

@troyharvey
Created September 18, 2019 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troyharvey/ef4b1c9e506e1dbf02490cc8a69d197e to your computer and use it in GitHub Desktop.
Save troyharvey/ef4b1c9e506e1dbf02490cc8a69d197e to your computer and use it in GitHub Desktop.
Encrypt data after changing the APP_KEY
<?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