搜索
首页php框架LaravelLaravel 中的数据加密和解密

本指南解释了如何实现加密和解密 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 = [
        &#39;first_name&#39;, &#39;last_name&#39;, &#39;email&#39;, &#39;mobile&#39;, &#39;hashed_email&#39;, &#39;password&#39;
    ];

    // 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 = [
        &#39;first_name&#39;, &#39;last_name&#39;, &#39;email&#39;, &#39;mobile&#39;, &#39;hashed_email&#39;, &#39;password&#39;
    ];

    // 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,加密数据将无法恢复。

   摘要

  1. 模型加密:存储前使用setter方法加密数据,检索时使用getter方法解密。
  2. 控制器逻辑:控制器可以直接处理加密字段,无需额外的加密代码.
  3. 数据库配置:使用 TEXT 或 LONGTEXT 列作为加密字段。
  4. 安全注意事项:保护您的 APP_KEY 并在 getter 中使用异常处理来处理解密错误。

以上是Laravel 中的数据加密和解密的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:dev.to。如有侵权,请联系admin@php.cn删除
最后的Laravel版本:迁移教程最后的Laravel版本:迁移教程May 14, 2025 am 12:17 AM

Laravel的迁移系统在最新版本中提供了哪些新功能和最佳实践?1.新增了nullableMorphs()用于多态关系。2.引入了after()方法来指定列顺序。3.强调处理外键约束以避免孤立记录。4.建议优化性能,如适当添加索引。5.提倡迁移的幂等性和使用描述性名称。

Laravel的最新LTS版本是什么?Laravel的最新LTS版本是什么?May 14, 2025 am 12:14 AM

Laravel10,释放的2023年,IstheLatestltSversion,支持Forthreyear。

保持更新:最新的Laravel版本中的最新功能保持更新:最新的Laravel版本中的最新功能May 14, 2025 am 12:10 AM

Laravel的最新版本引入了多个新功能:1.LaravelPennant用于管理功能标志,允许分阶段发布新功能;2.LaravelReverb简化了实时功能的实现,如实时评论;3.LaravelVite加速了前端构建过程;4.新的模型工厂系统增强了测试数据的创建;5.改进了错误处理机制,提供了更灵活的错误页面自定义选项。

在Laravel中实现软删除:逐步教程在Laravel中实现软删除:逐步教程May 14, 2025 am 12:02 AM

SoftleteTeinElelelverisling -Memptry -BraceChortsDevetus -teedeeceteveveledeveveledeecetteecetecetecedelave

当前Laravel版本:检查最新版本和更新当前Laravel版本:检查最新版本和更新May 14, 2025 am 12:01 AM

laravel10.xisthecurrentversion,offeringNewFeaturesLikeEnumSupportineloQuentModelsAndModersAndImpreverModeModeModelBindingWithenums.theSeupDatesEupDatesEnhanceCodereadability andSecurity andSecurity和butquirecareecarefulecarefulecarefulplanninganninganningalmplementAlimplemplemplemplemplemplempletationForupforupsupflade。

如何使用Laravel迁移:逐步教程如何使用Laravel迁移:逐步教程May 13, 2025 am 12:15 AM

laravelmigrationsStreamLinedAtabasemangementbyallowingbolAlyChemachangeStobEdeDinedInphpcode,whobeversion-controllolleDandShared.here'showtousethem:1)createMigrationClassestodeFinePerationFineFineOperationsLikeCreatingingModifyingTables.2)

查找最新的Laravel版本:快速简便的指南查找最新的Laravel版本:快速简便的指南May 13, 2025 am 12:13 AM

要查找最新版本的Laravel,可以访问官方网站laravel.com并点击右上角的"Docs"按钮,或使用Composer命令"composershowlaravel/framework|grepversions"。保持更新有助于提升项目安全性和性能,但需考虑对现有项目的影响。

使用Laravel的更新:使用最新版本的好处使用Laravel的更新:使用最新版本的好处May 13, 2025 am 12:08 AM

youshouldupdateTotheLateStlaravelVerverSionForPerformanceImprovements,增强的安全性,newfeatures,BetterCommunitySupport,and long-term-Maintenance.1)绩效:Laravel9'Selover9'seloquentormoptimizatizationenenhanceApplicationsPeed.2)secuse:laravel8InIntrododeDodecter.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具