shaiq01/laravel-mysql-encrypt

Laravel 9.x 数据库端 mysql 加密

dev-main 2024-08-07 14:03 UTC

This package is auto-updated.

Last update: 2024-09-07 14:12:05 UTC


README

Laravel/Lumen 在数据库端使用原生 AES_DECRYPT 和 AES_ENCRYPT 函数进行数据库加密。自动加密和解密模型中的字段。

安装

1. Composer

composer require danielpardamean/laravel-mysql-encrypt

2. 发布配置(可选)

Laravel

php artisan vendor:publish --provider="DanielPardamean\MysqlEncrypt\Providers\LaravelServiceProvider"

Lumen

mkdir -p config
cp vendor/danielpardamean/laravel-mysql-encrypt/config/config.php config/mysql-encrypt.php

3. 配置提供者

Laravel

  • 对于 Laravel 5.5 或更高版本,服务提供者将自动加载,请跳过此步骤。

  • 对于 Laravel 5.4 或更早版本,将以下内容添加到 config/app.php

'providers' => array(
    DanielPardamean\\MysqlEncrypt\\Providers\\LaravelServiceProvider::class
);

Lumen

  • 对于 Lumen,将以下内容添加到 bootstrap/app.php
$app->register(DanielPardamean\MysqlEncrypt\Providers\LumenServiceProvider::class);

4. 在 .env 文件中设置加密密钥

APP_AESENCRYPT_KEY=yourencryptionkey

更新模型

<?php

namespace App;

use DanielPardamean\MysqlEncrypt\Traits\Encryptable;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use Encryptable; // <-- 1. Include trait

    protected $encryptable = [ // <-- 2. Include columns to be encrypted
        'email',
        'first_name',
        'last_name',
        'telephone',
    ];
}

验证器

unique_encrypted

unique_encrypted:<table>,<field(optional)>

exists_encrypted

exists_encrypted:<table>,<field(optional)>

作用域

提供自定义本地作用域

whereEncrypted whereNotEncrypted orWhereEncrypted orWhereNotEncrypted orderByEncrypted

全局作用域 DecryptSelectScope 在使用 Encryptable 特性模型的模型中自动启动。

支持加密数据的模式列

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

// Once the table has been created, use ALTER TABLE to create VARBINARY
// or BLOB types to store encrypted data.
DB::statement('ALTER TABLE `users` ADD `first_name` VARBINARY(300)');
DB::statement('ALTER TABLE `users` ADD `last_name` VARBINARY(300)');
DB::statement('ALTER TABLE `users` ADD `email` VARBINARY(300)');
DB::statement('ALTER TABLE `users` ADD `telephone` VARBINARY(50)');

许可证

MIT 许可证 (MIT)。请参阅 许可证文件 以获取更多信息。