dustapplication / laravel-database-model-encryption
提供带有搜索加密字段的数据库加密/解密。
Requires
- php: >=7.1
- illuminate/database: ^5.7
README
使用 Laravel 的 Crypt 加密和解密模型属性的包
大多数客户都想加密他们的数据库。这样,如果有人获得了对数据库的访问权限,他们就不会看到实际的数据。但是问题在于,当开发者需要时,他们很难搜索加密数据。
本项目旨在创建一个“安装后即可使用”的包,可以轻松安装并加密和解密存储在数据库表中的 Eloquent 模型属性,最重要的是能够使用与 Laravel Eloquent 的 where 和 orWhere 类似的 whereEncrypted 和 orWhereEncrypted 函数来搜索加密的数据库字段。
主要功能
- 轻松加密和解密数据库字段
- 最小化配置
- 使用以下方式包含搜索加密数据:
whereEncrypted和orWhereEncrypted - 使用 Laravel 的 Facades
Crypt加密和解密字段
要求
- Laravel: 5.5, 5.6, 5.7 或 5.8
- PHP: 5.6 以上
模式要求
加密值通常比纯文本值长,有时长得多。您可能会发现,数据库表中的列宽需要更改以存储本包生成的加密值。
我们强烈建议将列类型更改为 TEXT 或 LONGTEXT
安装
步骤 1: Composer
通过 Composer 命令行
$ composer require dustapplication/laravel-database-model-encryption
步骤 2: 将 ServiceProvider 添加到您的 app/config.php 文件(Laravel 5.4 或以下)
将服务提供者添加到 config/app.php 配置文件中的 providers 数组中,如下所示
'providers' => [ ... \DustApplication\Encryption\Providers\EncryptServiceProvider::class, ],
用法
在您希望应用加密的任何 Eloquent 模型中使用 EncryptedAttribute 特性,并定义一个包含要加密的属性列表的 protected $encrypted 数组。
例如
use DustApplication\Encryption\Traits\EncryptedAttribute;
class User extends Eloquent {
use EncryptedAttribute;
/**
* The attributes that should be encrypted on save.
*
* @var array
*/
protected $encryptable = [
'first_name', 'last_name'
];
}
通过包含 EncryptedAttribute 特性,Eloquent 提供的 setAttribute()、getAttribute() 和 getAttributeFromArray() 方法被覆盖以包含一个额外的步骤。
搜索加密字段示例
可以通过调用与 Laravel Eloquent 的 where 和 orWhere 类似的 whereEncrypted 和 orWhereEncrypted 函数来搜索加密字段。
namespace App\Http\Controllers; use App\User; class UsersController extends Controller { public function index(Request $request) { $user = User::whereEncrypted('first_name','john') ->orWhereEncrypted('last_name','!=','Doe')->firstOrFail(); return $user; } }
注意
建议在小型数据集上使用加密搜索。在大量数据行上使用它将影响性能。
加密当前数据
如果您数据库中已有数据,可以使用 php artisan encryptable:encryptModel 'App\User' 命令对其进行加密。
另外,您还可以使用 php artisan encryptable:decryptModel 'App\User' 命令进行解密。
注意:您必须首先实现 Encryptable 特性并设置 $encryptable 属性
存在和唯一验证规则
如果您正在使用与加密值一起的 exists 和 unique 规则,请将其替换为 exists_encrypted 和 unique_encrypted php $validator = validator(['email'=>'foo@bar.com'], ['email'=>'exists_encrypted:users,email']); $validator = validator(['email'=>'foo@bar.com'], ['email'=>'unique_encrypted:users,email']);
常见问题解答
我能否使用除了 crypt 之外的加密方法?
目前不行,但未来可能会在更新中包括它
我能否搜索加密数据?
YES!您将能够搜索由本软件包加密的属性,因为。如果您需要搜索数据,请使用whereEncrypted和orWhereEncrypted函数
User::whereEncrypted('email','test@gmail.com')->orWhereEncrypted('email','test2@gmail.com')->firstOrFail();
一旦模型使用EncryptedAttribute,它将自动添加到eloquent中
我能否加密所有User模型的数据?
除了ID之外,您还可以加密您想要的一切
例如:在加密的电子邮件上登录
$user = User::whereEncrypted('email','test@gmail.com')->filter(function ($item) use ($request) {
return Hash::check($password, $item->password);
})->where('active',1)->first();
致谢
本软件包受到了以下项目的启发:austinheap/laravel-database-encryption magros/laravel-model-encryption
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。