codiant/dbaesencrypt

Laravel MySql AES 加密/解密

dev-master / 1.0.x-dev 2021-02-11 07:02 UTC

This package is not auto-updated.

Last update: 2024-09-19 23:47:59 UTC


README

Laravel MySql AES 加密/解密

Laravel 5.x 数据库加密在 mysql 端,使用原生 mysql 函数 AES_DECRYPT 和 AES_ENCRYPT
自动加密和解密模型中的签名字段/列
可以使用 Eloquent/Model 的所有函数
你可以在加密列之间执行操作 "=>, <',' between ',' LIKE '

1. 通过 Composer 安装包

$ composer require codiant/dbaesencrypt

2. 配置提供者

如果你使用的是 Laravel 5.4 或更早版本,需要在 config/app.php 中添加并注释一行

'providers' => array(
    // Illuminate\Database\DatabaseServiceProvider::class,
    DevMaster10\\AESEncrypt\\Database\\DatabaseServiceProviderEncrypt::class
)

更新你的 Eloquent 模型

具有加密列的模型应该扩展 ModelEncrypt

namespace App\Models;

use DevMaster10\AESEncrypt\Database\Eloquent;

class Persons extends ModelEncrypt
{    
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'tb_persons';

    /**
     * The attributes that are encrypted.
     *
     * @var array
     */
    protected $fillableEncrypt = [
        'name'
    ];

     /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
                'name',
                'description',
                ];
}

创建支持加密列的表

它为 Schema 添加了新功能,你可以在迁移中使用

    Schema::create('tb_persons', function (Blueprint $table) {
        // here you do all columns supported by the schema builder
        $table->increments('id')->unsigned;
        $table->string('description', 250);
        $table ->unsignedInteger('created_by')->nullable();
        $table ->unsignedInteger('updated_by')->nullable();
    });
    
    // once the table is created use a raw query to ALTER it and add the BLOB, MEDIUMBLOB or LONGBLOB
    DB::statement("ALTER TABLE tb_persons ADD name MEDIUMBLOB after id");  

});

在 .env 和配置文件中设置加密密钥

Set in .env file
APP_AESENCRYPT_KEY=yourencryptedkey

Set in config/services.php
'aesEncrypt' => [
    'key' => env('APP_AESENCRYPT_KEY'),
]

为解决认证模型的问题添加 BaseUser 类

Create BaseUser class in app/BaseUser.php for fixed problem of authenticable model problem
namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use DevMaster10\AESEncrypt\Database\Eloquent;

class BaseUser extends Eloquent\ModelEncrypt implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
}

在 Authenticatable 模型中扩展 BaseUser 类。