本指南解释了如何实现加密和解密 Laravel 模型中的敏感数据。通过执行以下步骤,您可以 在将数据存储到数据库之前对其进行保护,并在存储时对其进行解密 正在检索它。
先决条件
- Laravel:确保您使用的是 Laravel 项目。
- 加密密钥:Laravel 在 .env 文件中自动生成 APP_KEY。该密钥由 Laravel 的加密服务使用。
第 1 步:在模型中设置加密
在模型中,我们将使用 Laravel 的 encrypt() 和 decrypt() 函数自动处理指定字段的加密和解密。
Doctor模型
使用加密和解密方法创建或更新Doctor模型。我们将在将名字、姓氏、电子邮件和手机等字段保存到数据库之前对其进行加密。
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;use IlluminateSupportFacadesCrypt;class Doctor extends Model{ protected $fillable = [ 'first_name', 'last_name', 'email', 'mobile', 'hashed_email', 'password' ]; // Automatically encrypt attributes when setting them public function setFirstNameAttribute($value) { $this->attributes['first_name'] = encrypt($value); } public function setLastNameAttribute($value) { $this->attributes['last_name'] = encrypt($value); } public function setEmailAttribute($value) { $this->attributes['email'] = encrypt($value); } public function setMobileAttribute($value) { $this->attributes['mobile'] = encrypt($value); } // Automatically decrypt attributes when getting them public function getFirstNameAttribute($value) { return decrypt($value); } public function getLastNameAttribute($value) { return decrypt($value); } public function getEmailAttribute($value) { return decrypt($value); } public function getMobileAttribute($value) { return decrypt($value); }}
说明
- Setter 方法:使用 set{AttributeName }Attribute() 在数据存储到数据库之前对数据进行加密。
- Getter 方法:从数据库检索数据时,使用 get{AttributeName}Attribute() 解密。
第 2 步:数据存储和检索的控制器
在控制器中,您可以处理验证并调用模型的 直接加密属性,无需额外加密/解密 步骤。
DoctorController
DoctorController 通过验证来处理注册
输入数据,通过模型对其进行加密,并将其保存在数据库中。
获取医生数据时,会自动解密
敏感字段。
<?phpnamespace AppHttpControllers;use IlluminateHttpRequest;use AppModelsDoctor;use IlluminateSupportFacadesHash;class DoctorController extends Controller{ public function register(Request $request) { // Validate the incoming request $validatedData = $request->validate([ 'first_name' => 'required|string|max:255', 'last_name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:doctors,email', 'mobile' => 'required|string|size:10|unique:doctors,mobile', 'password' => 'required|string|min:8|confirmed', ]); // Hash the email to ensure uniqueness $hashedEmail = hash('sha256', $validatedData['email']); // Create a new doctor record (model will handle encryption) $doctor = Doctor::create([ 'first_name' => $validatedData['first_name'], 'last_name' => $validatedData['last_name'], 'email' => $validatedData['email'], 'hashed_email' => $hashedEmail, 'mobile' => $validatedData['mobile'], 'password' => Hash::make($validatedData['password']), ]); return response()->json([ 'message' => 'Doctor registered successfully', 'doctor' => $doctor ], 201); } public function show($id) { // Fetch the doctor record (model will decrypt the data automatically) $doctor = Doctor::findOrFail($id); return response()->json($doctor); }}
说明
- register 方法:验证传入的请求,创建新的医生记录,并根据模型的加密方法自动加密名字、姓氏、电子邮件和手机等字段。
- show 方法:通过 ID 检索医生记录。这 模型的 getter 方法之前会自动解密敏感字段 返回数据。
步骤 3:数据库配置
确保敏感数据的 doctor 表列的长度足以处理加密数据(通常为 TEXT 或 LONGTEXT)。
迁移设置示例:
Schema::create('doctors', function (Blueprint $table) { $table->id(); $table->text('first_name'); $table->text('last_name'); $table->text('email'); $table->string('hashed_email')->unique(); // SHA-256 hashed email $table->text('mobile'); $table->string('password'); $table->timestamps();});
注意:由于加密值可能比明文长得多值,加密字段首选文本。
步骤 4:处理解密异常
为了增强错误处理,请将解密逻辑包装在模型 getter 的 try-catch 块中:
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;use IlluminateSupportFacadesCrypt;class Doctor extends Model{ protected $fillable = [ 'first_name', 'last_name', 'email', 'mobile', 'hashed_email', 'password' ]; // Automatically encrypt attributes when setting them public function setFirstNameAttribute($value) { $this->attributes['first_name'] = encrypt($value); } public function setLastNameAttribute($value) { $this->attributes['last_name'] = encrypt($value); } public function setEmailAttribute($value) { $this->attributes['email'] = encrypt($value); } public function setMobileAttribute($value) { $this->attributes['mobile'] = encrypt($value); } // Automatically decrypt attributes when getting them public function getFirstNameAttribute($value) { return decrypt($value); } public function getLastNameAttribute($value) { return decrypt($value); } public function getEmailAttribute($value) { return decrypt($value); } public function getMobileAttribute($value) { return decrypt($value); }}
附加说明
- 环境安全:确保 APP_KEY 安全地存储在 .env 文件中。此密钥对于加密/解密至关重要。
- 数据备份:如果数据完整性至关重要,请确保您有备份机制,因为没有正确的 APP_KEY,加密数据将无法恢复。
摘要
- 模型加密:存储前使用setter方法加密数据,检索时使用getter方法解密。
- 控制器逻辑:控制器可以直接处理加密字段,无需额外的加密代码.
- 数据库配置:使用 TEXT 或 LONGTEXT 列作为加密字段。
- 安全注意事项:保护您的 APP_KEY 并在 getter 中使用异常处理来处理解密错误。
以上是Laravel 中的数据加密和解密的详细内容。更多信息请关注PHP中文网其他相关文章!

Laravel受欢迎的原因包括其简化开发过程、提供愉快的开发环境和丰富的功能。1)它吸收了RubyonRails的设计理念,结合PHP的灵活性。2)提供了如EloquentORM、Blade模板引擎等工具,提高开发效率。3)其MVC架构和依赖注入机制使代码更加模块化和可测试。4)提供了强大的调试工具和性能优化方法,如缓存系统和最佳实践。

Django和Laravel都是全栈框架,Django适合Python开发者和复杂业务逻辑,Laravel适合PHP开发者和优雅语法。1.Django基于Python,遵循“电池齐全”哲学,适合快速开发和高并发。2.Laravel基于PHP,强调开发者体验,适合小型到中型项目。

PHP和Laravel不是直接可比的,因为Laravel是基于PHP的框架。1.PHP适合小型项目或快速原型开发,因其简单直接。2.Laravel适合大型项目或高效开发,因其提供丰富功能和工具,但学习曲线较陡,性能可能不如纯PHP。

laravelisabackendframeworkbuiltonphp,设计ForweBapplicationDevelopment.itfocusessonserver-sideLogic,databasemagemention和Applicationstructure和CanBeintegratedWithFrontendTechnologiesLikeLikeVue.jsorreActeReacterVue.jsorreActforforfull-stackDevefloct。

本文讨论了Laravel中的创建和使用自定义刀片指令以增强模板。它涵盖了定义指令,在模板中使用它们,并在大型项目中管理它们,强调了改进的代码可重复性和R等好处

本文讨论了使用组件在Laravel中创建和自定义可重复使用的UI元素,从而为组织提供最佳实践并建议增强包装。

文章讨论了使用Laravel的路由来创建SEO友好的URL,涵盖最佳实践,规范的URL和SEO优化工具。WordCount:159

Laravel的工匠控制台可以自动化任务,例如生成代码,运行迁移和调度。关键命令包括:控制器,迁移和DB:种子。可以为特定需求创建自定义命令,增强工作流效率。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

禅工作室 13.0.1
功能强大的PHP集成开发环境

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3汉化版
中文版,非常好用