oriamdev / encryption-db-fields
该包的最新版本(dev-master)没有可用的许可证信息。
此包允许对数据库中所有关键字段进行双向加密。允许通过加密字段进行搜索。
dev-master
2022-05-29 12:18 UTC
This package is auto-updated.
Last update: 2024-09-29 06:03:21 UTC
README
此包允许对数据库中所有关键字段进行双向加密。
允许通过加密字段进行搜索。
安装
您可以通过composer安装此包
composer require oriamdev/encryption-db-fields
设置Eloquent模型
1 - 首先,当您想要加密字段时,需要将特质 EncryptAttributesTrait 添加到模型中。
use EncryptAttributesTrait;
2 - 定义要加密的字段数组
protected array $encrypts = ['name', 'email'];
3 - 如果您想要通过加密字段进行搜索,则需要将数组 $searchableEncrypts 添加到模型中。
protected array $searchableEncrypts = ['name', 'email'];
调整数据库表结构
备注
- 要加密的字段必须是文本类型。
- 对于每个可搜索的字段,您需要将名为
field_signature的字符串字段添加到迁移中
Schema::create('users', function (Blueprint $table) { $table->id(); $table->text('name'); $table->text('email'); $table->string('email_signature',10)->index(); $table->string('name_signature', 10)->index(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });
迁移数据库
php artisan migrate
CRUD操作
CRUD操作以相同的方式进行,加密和解密字段的流程由特质 EncryptAttributesTrait 负责
验证规则
laravel的验证规则 unique and exists 不起作用,但不必担心。该包有一个验证规则 Oriamdev\EncryptionUserDbAuth\Rules\Encrypted。构造函数需要模型的完全限定名称。 User::class or Post::class
检查验证字段是否唯一
创建加密规则的新实例后,可以传递unique方法
$request->validate([ 'email' => [(new Encrypted(User::class))->unique()], ]);
如果验证失败,规则返回 validation:unique 的默认值
检查验证字段是否存在
创建加密规则的新实例后,可以传递exists方法
$request->validate([ 'email' => [(new Encrypted(User::class))->unique()], ]);
如果验证失败,规则返回 validation:unique 的默认值
$request->validate([ 'name' => [(new Encrypted(User::class))->exists()] ]);
通过加密字段进行搜索
$user = User::findByEncrypt('email', 'mario@oriamdev.com');
方法 findByEncrypt 返回模型实例或不存在时返回 null。