Laravel’s encryption system securely encrypts and decrypts data using AES-256-CBC cipher with a base64-encoded application key, ensuring data privacy and integrity.

Key Points

  • Laravel uses AES-256-CBC cipher by default for secure data encryption and decryption.
  • Encryption key is base64-encoded and stored safely in the .env file under APP_KEY.
  • Laravel’s Encrypter class provides simple APIs for encrypting and decrypting data efficiently.
Digittrix Blog Author Image

Web Developer

Pragati S.

3 min read

3+ yrs of crafting high-performance websites with clean code and modern tech—turning ideas into digital experiences.

Laptop showing the Laravel logo with a graphic representing encryption and decryption on the side

If you are looking for website development services that include robust security features like custom encryption, leveraging Laravel’s built-in encryption system is a smart choice. This guide will walk you through creating a secure encryption and decryption system using Laravel (≥6.0) and PHP (≥7.2), helping you protect sensitive data in your custom web development projects.

Enhance campus security and streamline student tracking—learn how biometric attendance systems are transforming colleges.

Step 1: Generate a Custom Encryption Key

Laravel uses an application key to encrypt and decrypt data securely. This key is stored in the .env file as APP_KEY. To use a custom key, you first need to generate one. Laravel provides a convenient artisan command for this:

                                        php artisan key:generate --show

                                        
                                    

This command outputs a base64-encoded key similar to:

                                        base64:HA6Hm5LBe4Jacr2PK7gdNOgewwBQOk1k9zu1Wyy3kDA=

                                        
                                    

Save this key securely in your .env file under APP_KEY. If you want to generate your key programmatically, you can do:

                                        $key = base64_encode(random_bytes(32));

                                        
                                    

Step 2: Create Custom Encryption and Decryption Functions

Laravel’s Crypt facade uses the APP_KEY by default. However, for advanced custom web development, you may want to use your key explicitly. Here's how you can create custom encrypt and decrypt methods in your controller:

                                        namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Str;
class UsersController extends Controller
{
    public function customEncrypt($data)
    {
        $customKey = env('APP_KEY');
        // Strip 'base64:' if present
        if (Str::startsWith($customKey, 'base64:')) {
            $customKey = substr($customKey, 7);
        }
        $key = base64_decode($customKey);
        $encrypter = new Encrypter($key, config('app.cipher')); // Cipher: AES-256-CBC by default
        return $encrypter->encrypt($data);
    }
                                        
                                    

Explanation:

  • The key is base64-decoded because Laravel expects the key in binary format.

  • The Encrypter class is instantiated with the custom key and cipher (default is AES-256-CBC).

  • The encrypt() method encrypts your plain text, and decrypt() reverses it.

  • Exceptions during decryption are gracefully handled.

Now create a custom decryption function. Here is an example code:

                                            public function customDecrypt($encryptedData)
    {
        try {
            $customKey = env('APP_KEY');
            // Strip 'base64:' if present
            if (Str::startsWith($customKey, 'base64:')) {
                $customKey = substr($customKey, 7);
            }
            $key = base64_decode($customKey);
            $encrypter = new Encrypter($key, config('app.cipher'));
            return $encrypter->decrypt($encryptedData);
        } catch (DecryptException $e) {
            // Handle the exception
            return 'Decryption failed: ' . $e->getMessage();
        }
    }
                                        
                                    

Explanation:

  • decrypt($encryptedData): Decrypts the encrypted data using the custom key.

  • DecryptException: Catches any issues that might occur during decryption.

Step 3: Confirm or Set the Encryption Cipher

In Laravel, you can configure the encryption cipher in config/app.php:

                                        'cipher' => 'AES-256-CBC',

                                        
                                    

This is the recommended cipher for secure encryption. If needed, you can switch to 'AES-128-CBC' or other supported ciphers.

Step 4: Implement Routes and Blade View for Encryption and Decryption

To allow users to encrypt and decrypt data via web interface, add routes in web.php:

use App\Http\Controllers\UsersController;

                                        Route::post('/encrypt',  [UsersController::class, 'encryptData']);

Route::post('/decrypt',  [UsersController::class, 'decryptData']);

                                        
                                    

Create a Blade
view resources/views/Scripts/EncryptionDecryption.blade.php:

                                        <!DOCTYPE html>
<html>

<head>
    <title>Encrypt & Decrypt Text</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>

<body>
    <div class="container mt-5">
        <h2>Encrypt & Decrypt Text</h2>

        <!-- Encrypt Form -->
        <form method="POST" action="/encrypt" class="mb-4">
            @csrf
            <div class="form-group">
                <label><strong>Encrypt Text</strong></label>
                <input type="text" name="encrypt_text" class="form-control" placeholder="Enter text to encrypt"
                    required>
            </div>
            <button type="submit" class="btn btn-primary">Encrypt</button>
        </form>

        @if (!empty($encrypted))
            <div class="alert alert-info">
                <strong>Encrypted Text:</strong>
                <input type="text" class="form-control" value="{{ $encrypted }}" readonly>
            </div>
        @endif

        <!-- Decrypt Form -->
        <form method="POST" action="/decrypt">
            @csrf
            <div class="form-group">
                <label><strong>Decrypt Text</strong></label>
                <input type="text" name="decrypt_text" class="form-control" placeholder="Enter text to decrypt"
                    value="{{ $encrypted ?? '' }}">
            </div>
            <button type="submit" class="btn btn-success">Decrypt</button>
        </form>

        @if (!empty($decrypted))
            <div class="mt-3 alert alert-success">
                <strong>Decrypted Text:</strong> {{ $decrypted }}
            </div>
        @endif
    </div>
</body>

</html>

                                        
                                    

Step 5: Controller Methods to Handle Form Submission

Add the following methods in your UsersController:

                                        public function encryptData(Request $request)
    {
        $encrypt_text = $request->encrypt_text;
        $encrypted = $this->customEncrypt($encrypt_text);


        return view('Scripts.EncryptionDecryption', [
            'encrypt_text' => $encrypt_text,
            'encrypted'    => $encrypted,
            'decrypt_text' => '', // leave blank for now
            'decrypted'    => ''
        ]);
    }


    public function decryptData(Request $request)
    {
        $decrypt_text = $request->decrypt_text;
        $encrypted_text = $request->encrypted_text;
        $original_encrypt_input = $request->original_encrypt_text;


        try {
            $decrypted = $this->customDecrypt($decrypt_text);
        } catch (\Exception $e) {
            $decrypted = 'Invalid encrypted text.';
        }


        return view('Scripts.EncryptionDecryption', [
            'encrypt_text' => $original_encrypt_input, // original input to encrypt
            'encrypted'    => $encrypted_text,         // the encrypted text
            'decrypt_text' => $decrypt_text,           // what user submitted for decryption
            'decrypted'    => $decrypted               // result after decryption
        ]);
    }
                                        
                                    

Output:-

Why Hire Developers for Custom Encryption?

Implementing secure encryption and decryption requires expertise. When you hire Laravel developers for your custom web development projects, you get professionals who understand Laravel's encryption internals, ensuring your application data is protected with best practices.

Our website development services specialize in building secure and scalable Laravel applications tailored to your business needs. From custom encryption to complex business logic, we help you stay ahead in security and performance.

Final Words

By integrating custom encryption and decryption functions in Laravel, you significantly enhance your application's data security. Whether you provide website development services or are simply strengthening your own Laravel apps, this guide is a practical tool. If you’re scaling your business or need more specialized development, consider working with experts—Hire Laravel Developers who understand security best practices inside and out.

Do you want help implementing this?

Get a summary via Google for

$0

Get Help Now!

Tech Stack & Version

 Frontend

  • HTML
  • CSS
  • JS

 Backend

  • Laravel 10
  • PHP 8.1

 Deployment

  • Apache
  • Nginx
  • DigitalOcean
  • Linode
img

©2025Digittrix Infotech Private Limited , All rights reserved.