tapanderasari/laravel-mysql-encrypt

Laravel 数据库加密(MySQL端)

v1.0.5 2024-05-29 09:13 UTC

README

Total Downloads Latest Stable Version License

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

安装

1. Composer

composer require tapanderasari/laravel-mysql-encrypt

2. 发布配置(可选)

Laravel

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

Lumen

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

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

APP_AESENCRYPT_KEY=yourencryptionkey

更新模型

<?php

namespace App;

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

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

    public array $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 whereEncryptedLike scopeOrderByEncryptedSort

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

支持加密数据的模式列

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('password');
    $table->binary('first_name',300); // VARBINARY(300) for laravel 11.x and above versions
    $table->rememberToken();
    $table->timestamps();
});

// for laravel 10.x and below version, 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)');

对现有数据进行加密实现

为此,您可以创建一个命令,如下所示

php artisan make:command EncryptionForExistingData

在这个命令中,您使用没有全局作用域 DecryptSelectScope 来检索现有表或模型数据。

您可以通过点击下面的示例按钮来参考示例

许可

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