socratesldduarte / laravel-database-encryption
通过Eloquent自动加密和解密数据库
Requires (Dev)
- orchestra/testbench: ^6.4
- phpunit/phpunit: ^9.4
README
使用Laravel的Crypt对Laravel模型属性进行加密和解密的包
主要功能
- 轻松加密和解密数据库字段
- 最小配置
- 使用以下方式包含搜索加密数据:
whereEncrypted和orWhereEncrypted - 版本1.1包括使用以下方式对加密数据进行排序:
orderByEncrypted - 使用Laravel的Facades
Crypt进行字段加密和解密
要求
- Laravel: >= 5
- PHP: >= 7.3
模式要求
加密值通常比纯文本值长,有时长得多。您可能会发现您数据库表中的列宽度需要更改,以存储此包生成的加密值。
我们强烈建议将列类型更改为 TEXT 或 LONGTEXT
安装
步骤1:Composer
通过Composer命令行
$ composer require socratesldduarte/laravel-database-encryption
步骤2:将ServiceProvider添加到您的app/config.php文件中(Laravel 5.4或以下版本)
将服务提供程序添加到config/app.php配置文件中的providers数组中,如下所示
'providers' => [ ... \socratesldduarte\DBEncryption\Providers\DBEncryptionServiceProvider::class, ],
用法
在任何您希望应用加密的Eloquent模型中使用EncryptedAttribute特质,并定义一个包含要加密的属性列表的protected $encrypted数组。
例如
use socratesldduarte\DBEncryption\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_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']);
常见问题解答
我可以搜索加密数据吗?
是的!您将能够搜索由此包加密的属性,因为如果您需要搜索数据,请使用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();
致谢
此包是从以下包派生的:elgibor-solution/laravel-database-encryption 此包的灵感来自以下包:austinheap/laravel-database-encryption magros/laravel-model-encryption DustApplication/laravel-database-model-encryption
许可证
麻省理工学院许可证(MIT)。有关更多信息,请参阅许可文件。