|
| 1 | +# Laravel MySql AES Encrypt/Decrypt |
| 2 | + |
| 3 | +Laravel database encryption at database side using native AES_DECRYPT and AES_ENCRYPT functions. |
| 4 | +Automatically encrypt and decrypt fields in your Models. |
| 5 | + |
| 6 | +## 1. Install |
| 7 | +```bash |
| 8 | +composer require chr15k/laravel-mysql-encrypt |
| 9 | +``` |
| 10 | + |
| 11 | +## 2. Publish config (optional) |
| 12 | +```bash |
| 13 | +php artisan vendor:publish --provider="Chr15k\MysqlEncrypt\MysqlEncryptServiceProvider" |
| 14 | +``` |
| 15 | + |
| 16 | +## 3. Configure Provider (Laravel 5.4 or earlier) |
| 17 | +For Laravel 5.4 or earlier, you'll need to add the following to config/app.php: |
| 18 | + |
| 19 | +```php |
| 20 | +'providers' => array( |
| 21 | + Chr15k\\MysqlEncrypt\\MysqlEncryptServiceProvider::class |
| 22 | +) |
| 23 | +``` |
| 24 | + |
| 25 | +## 4. Set encryption key in `.env` file |
| 26 | +``` |
| 27 | +APP_AESENCRYPT_KEY=yourencryptionkey |
| 28 | +``` |
| 29 | + |
| 30 | +## Update Models |
| 31 | +```php |
| 32 | +<?php |
| 33 | + |
| 34 | +namespace App; |
| 35 | + |
| 36 | +use Chr15k\MysqlEncrypt\Traits\Encryptable; |
| 37 | +use Illuminate\Database\Eloquent\Model; |
| 38 | + |
| 39 | +class User extends Model |
| 40 | +{ |
| 41 | + use Encryptable; // <-- 1. Include trait |
| 42 | + |
| 43 | + protected $encryptable = [ // <-- 2. Include columns to be encrypted |
| 44 | + 'email', |
| 45 | + 'first_name', |
| 46 | + 'last_name', |
| 47 | + 'telephone', |
| 48 | + ]; |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +## Schema columns to support encrypted data |
| 53 | +```php |
| 54 | +Schema::create('users', function (Blueprint $table) { |
| 55 | + $table->bigIncrements('id'); |
| 56 | + $table->string('password'); |
| 57 | + $table->rememberToken(); |
| 58 | + $table->timestamps(); |
| 59 | +}); |
| 60 | + |
| 61 | +// Once the table has been created, use ALTER TABLE to create VARBINARY |
| 62 | +// or BLOB types to store encrypted data. |
| 63 | +DB::statement('ALTER TABLE `users` ADD `first_name` VARBINARY(300)'); |
| 64 | +DB::statement('ALTER TABLE `users` ADD `last_name` VARBINARY(300)'); |
| 65 | +DB::statement('ALTER TABLE `users` ADD `email` VARBINARY(300)'); |
| 66 | +DB::statement('ALTER TABLE `users` ADD `telephone` VARBINARY(50)'); |
| 67 | +``` |
0 commit comments