搜索
首页php框架LaravelLaravel 中的数据加密和解密
Laravel 中的数据加密和解密Dec 12, 2024 am 11:50 AM
laravelcadai敏感数据

本指南介绍了如何在 Laravel 模型中实现敏感数据的加密和解密。通过执行以下步骤,您可以在将数据存储到数据库之前保护数据并在检索数据时对其进行解密。

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中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
laravel单点登录方法详解laravel单点登录方法详解Jun 15, 2022 am 11:45 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于单点登录的相关问题,单点登录是指在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统,下面一起来看一下,希望对大家有帮助。

一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

laravel中guard是什么laravel中guard是什么Jun 02, 2022 pm 05:54 PM

在laravel中,guard是一个用于用户认证的插件;guard的作用就是处理认证判断每一个请求,从数据库中读取数据和用户输入的对比,调用是否登录过或者允许通过的,并且Guard能非常灵活的构建一套自己的认证体系。

laravel中asset()方法怎么用laravel中asset()方法怎么用Jun 02, 2022 pm 04:55 PM

laravel中asset()方法的用法:1、用于引入静态文件,语法为“src="{{asset(‘需要引入的文件路径’)}}"”;2、用于给当前请求的scheme前端资源生成一个url,语法为“$url = asset('前端资源')”。

实例详解laravel使用中间件记录用户请求日志实例详解laravel使用中间件记录用户请求日志Apr 26, 2022 am 11:53 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于使用中间件记录用户请求日志的相关问题,包括了创建中间件、注册中间件、记录用户访问等等内容,下面一起来看一下,希望对大家有帮助。

laravel中间件基础详解laravel中间件基础详解May 18, 2022 am 11:46 AM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于中间件的相关问题,包括了什么是中间件、自定义中间件等等,中间件为过滤进入应用的 HTTP 请求提供了一套便利的机制,下面一起来看一下,希望对大家有帮助。

laravel的fill方法怎么用laravel的fill方法怎么用Jun 06, 2022 pm 03:33 PM

在laravel中,fill方法是一个给Eloquent实例赋值属性的方法,该方法可以理解为用于过滤前端传输过来的与模型中对应的多余字段;当调用该方法时,会先去检测当前Model的状态,根据fillable数组的设置,Model会处于不同的状态。

laravel路由文件在哪个目录里laravel路由文件在哪个目录里Apr 28, 2022 pm 01:07 PM

laravel路由文件在“routes”目录里。Laravel中所有的路由文件定义在routes目录下,它里面的内容会自动被框架加载;该目录下默认有四个路由文件用于给不同的入口使用:web.php、api.php、console.php等。

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脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
1 个月前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

mPDF

mPDF

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

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具