adityadarma / laravel-database-cryptable
为Laravel的加密值数据库
Requires
- php: ^8.0
- laravel/framework: ^9.0|^10.0|^11.0
README
Laravel数据库加密,以确保数据安全。
Laravel安装说明
在终端中,从项目根目录运行
composer require adityadarma/laravel-database-cryptable
支持
- MYSQL
- MariaDB
- PostgreSQL(需要pgcrypto扩展)
用法
在您希望应用加密的任何Eloquent模型中使用CryptableAttribute
特性,并定义一个包含要加密的属性列表的protected $encryptable
数组。
例如
use AdityaDarma\LaravelDatabaseCryptable\Traits\CryptableAttribute; class User extends Eloquent { use CryptableAttribute; /** * The attributes that should be encrypted on save. * * @var array */ protected $encryptable = [ 'first_name', 'last_name' ]; }
通过包含CryptableAttribute
特性,Eloquent提供的setAttribute()
、getAttribute()
和getAttributeFromArray()
方法被重写,以包含一个额外的步骤。
搜索加密字段示例
可以通过调用类似Laravel Eloquent的where
和orWhere
的whereEncrypted
和orWhereEncrypted
函数来搜索加密字段。可以通过调用orderByEncrypted
来对加密数据进行排序,类似于Laravel Eloquent的orderBy
。
namespace App\Http\Controllers; use App\Models\User; class UsersController extends Controller { public function index(Request $request) { $user = User::whereEncrypted('first_name','john') ->orWhereEncrypted('last_name','!=','Doe') ->orderByEncrypted('last_name', 'asc') ->firstOrFail(); return $user; } }
加密现有数据
如果您数据库中已有数据,可以使用php artisan crypt:encrypt User
命令对其进行加密。
此外,您还可以使用php artisan crypt:decrypt 'User
命令对其进行解密。
注意:您必须首先实现CryptableAttribute
特性并设置$encryptable
属性
存在和唯一验证规则
如果您使用存在和唯一规则与加密值,请将其替换为exists_encrypted和unique_encrypted php $validator = validator(['email'=>'foo@bar.com'], ['email'=>'unique_encrypted:users,email']);
我能加密我的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
- DustApplication/laravel-database-model-encryption
- elgiborsolution/laravel-database-encryption
- NdukZ/laravel-database-encryption-pgsql
许可
本包采用MIT许可。祝您享受!