Laravel 10 How to Use Laravel's Encryption for Data Security

Hello Artisan, today I'll show you how to use Laravel encryption for data security. Laravel uses OpenSSL encryption library, which provides robust encryption algorithms. For more info about the OpenSSL encryption library, see here. So, no more talk let's see how we can encrypt secret data in our application. 

 

So we'll use encryptString() method of Crypt class for encrypt our data and decryptString() for decrypt our data. So at first, we'll create a controller firing the below command

php artisan make:controller UserController

It'll create a controller under app/Http/Controllers, open the file, and put checkEncryption() method in your controller. Look at the below source code.

filename.ext
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Crypt;

class UserController extends Controller
{
    public function checkEncryption()
    {
        $encrypted = Crypt::encryptString('Sensitive data');

        $decrypted = Crypt::decryptString($encrypted);

        dd($encrypted,$decrypted);
    }
}

Which produces the below result:

So as we see, after decrypting our encrypted data we get the real data that we encrypted called “Sensitive Data”. So, like that, we can protect our data, especially in API's. And one thing, please make sure you've set your APP_KEY in .env file, because by default, Laravel uses the APP_KEY specified in the .env file as the encryption key.

That's it for today. I hope it'll be helpful in upcoming projects. Thanks for reading. 🙂