Home >PHP Framework >Laravel >Data encryption and decryption in Laravel

Data encryption and decryption in Laravel

Jennifer Aniston
Jennifer AnistonOriginal
2024-12-12 11:50:02311browse

This guide explains how to implement encryption and decryption of sensitive data in Laravel models. By performing the following steps, you can protect the data before storing it in the database and decrypt it when retrieving the data.

Data encryption and decryption in Laravel

Prerequisites

  • Laravel: Make sure you are using a Laravel project.
  • Encryption key: Laravel automatically generates APP_KEY in the .env file. This key is used by Laravel's encryption service.

Step 1: Set up encryption in the model

In the model, we will use Laravel's encrypt() and decrypt() functions to automatically handle the encryption and decryption of the specified fields.

Doctor Model

Create or update a Doctor model using encryption and decryption methods. We will encrypt fields such as first name, last name, email, and mobile phone before saving them to the database.

<?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);
    }}

Description

  • Setter method: Use set{AttributeName }Attribute() to encrypt the data before storing it in the database.
  • Getter method: Use get{AttributeName}Attribute() to decrypt when retrieving data from the database.

Step 2: Controller for data storage and retrieval

In the controller you can handle validation and call the model's Directly encrypt attributes without additional encryption/decryption step.

DoctorController

DoctorController handles registration through validation Enter the data, encrypt it through the model, and save it in the database. When doctor data is obtained, it will be automatically decrypted Sensitive fields.

<?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);
    }}

Description

  • register method: Verify the incoming request, create a new doctor record, and automatically encrypt fields such as first name, last name, email, and mobile phone based on the model's encryption method.
  • show method: Retrieve physician records by ID. this Sensitive fields will be automatically decrypted before the model's getter method Return data.

Step 3: Database configuration

Ensure that the doctor table columns for sensitive data are long enough to handle encrypted data (usually TEXT or LONGTEXT).

Example of migration settings:

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();});

Note: Since encrypted values ​​may be much longer than plain text, text is preferred for encrypted fields.

Step 4: Handle decryption exceptions

To enhance error handling, wrap the decryption logic in a try-catch block in the model getter:

<?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);
    }}

Additional Notes

  • Environmental Security: Make sure APP_KEY is stored securely in the .env file. This key is essential for encryption/decryption.
  • Data Backup: If data integrity is critical, make sure you have a backup mechanism in place, as encrypted data will be unrecoverable without the correct APP_KEY.

Summary

  1. Model encryption: Use the setter method to encrypt data before storage, and use the getter method to decrypt it during retrieval.
  2. Controller logic: The controller can handle encrypted fields directly without additional encryption code.
  3. Database configuration: Use TEXT or LONGTEXT columns as encrypted fields.
  4. Security Note: Secure your APP_KEY and use exception handling in the getter to handle decryption errors.

The above is the detailed content of Data encryption and decryption in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Data Encryption and Decryption in LaravelNext article:None