How to Encrypt and Decrypt Messages in Laravel

June 27, 2023
Written by
Temitope Taiwo Oyedele
Contributor
Opinions expressed by Twilio contributors are their own
Reviewed by

How to Encrypt and Decrypt Messages in Laravel

In today's digital world, data security is of utmost importance. Web applications often deal with sensitive information that needs to be protected from unauthorized access. Laravel, a popular PHP framework, provides convenient methods for encrypting and decrypting data using the Crypt facade. This tutorial will show you how to use the Crypt facade to secure messages in Laravel applications.

Prerequisites

To successfully run the example and perform message encryption and decryption using Laravel's Crypt facade, you need the following:

  • The Laravel installer. You can refer to the Laravel documentation for detailed instructions on how to install Laravel.
  • PHP 8.2

Why is encryption important?

Encryption plays an essential role in data security because it helps to protect data from unauthorized access. It works by converting data into an unreadable format, known as ciphertext, which allows only authorized users with the decryption key to convert it back into its original readable format, known as plaintext.

There are many different types of encryption algorithms, each with its own strengths and weaknesses. Some of them include:

Laravel encryption basics

Before diving into the encryption process, it's essential to understand the basics of Laravel's encryption features and its configuration settings. Laravel supports symmetric encryption, where the same key is used for both encryption and decryption. It utilizes PHP's OpenSSL extension, making it compatible with multiple encryption algorithms like AES-256-CBC, AES-128-CBC, and more. These algorithms provide strong encryption for data protection.

Configuring encryption settings in Laravel involves updating the config/app.php file. Here, you can define the default encryption algorithm, specify the encryption key, and configure other encryption-related settings.

Overview of the Crypt facade

The Crypt facade in Laravel offers a simple and consistent API for encrypting and decrypting data. It provides a range of methods for encrypting and decrypting data, including the encrypt() and decrypt() methods. The Crypt facade uses a strong encryption algorithm, such as AES-256, to encrypt and decrypt data. This ensures that the data is protected from unauthorized access.

To use the Crypt facade, simply reference it using the Crypt alias:

use Illuminate\Support\Facades\Crypt;

Generating an encryption key

Before diving into message encryption, it is important to generate a unique encryption key. This key ensures the confidentiality and security of the encrypted data. Laravel simplifies the key generation process by providing an Artisan command. To generate an encryption key, open your terminal and run the following command:

php artisan key:generate

The new encryption key is stored in the .env file. The app/config/app.php file then loads the encryption key from the .env file. of your Laravel application. If you do not run the command, Laravel will use a default encryption key. However, this default encryption key is not secure.

Encrypting a message

To encrypt a message you use the encrypt method. Let's consider an example where we want to encrypt a user's email address. Here's what the code would look like:

use Illuminate\Support\Facades\Crypt;

$message = 'your message';
$encryptedMessage = Crypt::encrypt($message);

In the above code, we first import the Crypt facade, and then we encrypt a message using the encrypt() method. The resulting encrypted message is stored in the $encryptedMessage variable.

Decrypting a message

To decrypt an encrypted message you use the decrypt method. Following our previous example, let's decrypt the encrypted message:

$decryptedEmail = Crypt::decrypt($encryptedMessage);

In the code snippet above, we utilize the decrypt() method to decrypt the contents of the $encryptedMessage variable, resulting in the original email address stored in $decryptedMessage.

Example application: encrypting and decrypting a message

To demonstrate the usage of the Crypt facade for encrypting and decrypting messages, let's consider a simple Laravel application with a form where users can enter a message, and the application will encrypt and display the encrypted message.

Set up the project

Create a new Laravel project and change into the project by running the following commands in your terminal:

composer create-project laravel/laravel message-encryption
cd message-encryption

Create the encryption controller

The next step is to generate a new controller called EncryptionController by running the following command:

php artisan make:controller EncryptionController

Once we’ve done that, open it up (app/Http/Controllers/EncryptionController.php) and replace the code with the following:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class EncryptionController extends Controller
{
    public function encrypt(Request $request)
    {
        $message = $request->input('message');
        $encryptedMessage = Crypt::encrypt($message);
        return redirect('/')->with('encryptedMessage', $encryptedMessage);
    }

    public function decrypt(Request $request)
    {
        $encryptedMessage = $request->input('encrypted_message');
        $decryptedMessage = Crypt::decrypt($encryptedMessage);
        return redirect('/')->with('decryptedMessage', $decryptedMessage);
    }
}

Let’s break it down and explain what it does:

  • The encrypt() method accepts a Request object as a parameter, which represents the incoming HTTP request, and retrieves the message parameter from it using the call to $request->input('message').
  • The retrieved message is then encrypted using the Crypt::encrypt() method, provided by the Crypt facade. The encrypted message is assigned to the $encryptedMessage variable.
  • The method then redirects back to the '/' route using redirect('/') and attaches the encrypted message to the session using the with() method, making it available for display on the page.
  • The decrypt() method similar to the encrypt() method accepts a Request object, retrieves the encrypted_message input, and decrypts it using the Crypt::decrypt() method.

The decrypted message is assigned to the $decryptedMessage variable, and then the method redirects back to the '/' route, attaching the decrypted message to the session.

Define the routes

Open the routes/web.php file and replace the existing code with the following:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EncryptionController;

Route::get('/', function () {
    return view('encrypt');
});

Route::post('/encrypt', [EncryptionController::class, 'encrypt']);
Route::post('/decrypt', [EncryptionController::class, 'decrypt']);

Create the view

The last thing we’ll be doing in this example is to create our form. In the resource/view directory, create a file called encrypt.blade.php  and inside it, add the following:

<!DOCTYPE html>
<html>
<head>
   <title>Message Encryption</title>
   <style>
label {
   display: block;
   margin-bottom: 5px;
}

input[type="text"] {
   width: 100%;
   padding: 10px;
   font-size: 16px;
   border: 1px solid #ccc;
   border-radius: 4px;
}

button[type="submit"] {
   padding: 10px 20px;
   font-size: 16px;
   background-color: #4caf50;
   color: white;
   border: none;
   border-radius: 4px;
   cursor: pointer;
}

.message-container p {
   background-color: #f9f9f9;
   padding: 10px;
   border: 1px solid #ccc;
   border-radius: 4px;
   word-wrap: break-word;
}

.form-container {
   border: 1px solid #ccc;
   padding: 20px;
   border-radius: 4px;
}

   </style>
</head>
<body>
<div class="form-container">
   <h2>Message Encryption</h2>

   @if (session('encryptedMessage'))
       <div class="message-container">
           <h3>Encrypted Message:</h3>
           <p>{{ session('encryptedMessage') }}</p>
       </div>
   @endif

   @if (session('decryptedMessage'))
       <div class="message-container">
           <h3>Decrypted Message:</h3>
           <p>{{ session('decryptedMessage') }}</p>
       </div>
   @endif

   <form action="/encrypt" method="POST">
       @csrf
       <label for="message">Enter Message:</label>
       <input type="text" id="message" name="message">
       <button type="submit">Encrypt</button>
   </form>

   <form action="/decrypt" method="POST">
       @csrf
       <label for="encrypted_message">Enter Encrypted Message:</label>
       <input type="text" id="encrypted_message" name="encrypted_message">
       <button type="submit">Decrypt</button>
   </form>
   </div>
</body>
</html>

All done! Let’s start the Laravel application by running the following command:

php artisan serve

Then, open your browser and navigate to http://localhost:8000. You should see the message encryption form. Enter a message in the "Enter Message" field and click the Encrypt button. The page will refresh and you will see the encrypted message displayed. Copy the encrypted message, paste it into the "Enter Encrypted Message" field, and click the Decrypt button. The page will refresh again, and you will see the decrypted message displayed.

An example of the encryption/unencryption app in action.

Congratulations! You have successfully created an application that uses the Crypt facade to encrypt and decrypt messages in Laravel.

Conclusion

Data security is critical to web application development, and Laravel provides robust encryption features to protect sensitive information. By following the steps outlined in this , you can effectively encrypt and decrypt messages in Laravel.

Remember to implement best practices, such as protecting encryption keys, using strong algorithms, and properly managing encrypted data. With Laravel's encryption capabilities, you can confidently ensure the security and integrity of your application's data.

Temitope Taiwo Oyedele is a software engineer and technical writer. He likes to write about things he’s learned and experienced.

"Privacy and Encryption" by Richard Patterson is licensed under CC BY 2.0.