Encryption and Decryption Example in Laravel

Hello Artisan

In this tutorial we will learn about laravel built in encryption. Do you know what is encryption? Encryption is a system where we convert a plain text to a message using some algorithms so that any third party user cannot read the information. 

Laravel's encrypter uses OpenSSL to provide AES-256 and AES-128 encryption. You are strongly encouraged to use Laravel's built-in encryption facilities and not attempt to roll your own "home grown" encryption algorithms. 

 

Step 1 : Configuration

Before starting the use of laravel encrytion, you have a prerequisites. Before using Laravel's encrypter, you must set a key option in your config/app.php configuration file. You should use the 

php artisan key:generate

command to generate this key since this Artisan command will use PHP's secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be insecure.

Our configuration is done. Now we can use laravel encryption in our system properly. Now our encrypted value will be secured. Let's see now how we can use laravel built in helper function to encrypt a value or message.

Encrypting A Value

You may encrypt a value using the encrypt helper. All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher.

  public function storeSecret(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $user->fill([
            'secret' => encrypt($request->secret),
        ])->save();
    }

 

Encrypting Without Serialization

Encrypted values are passed through serialize during encryption, which allows for encryption of objects and arrays.If you would like to encrypt and decrypt values without serialization, you may use the encryptString and decryptString methods of the Crypt facade: See the below example to understand clearly.

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString('Hello world.');

 

You may decrypt values using the decryptString helper function. See below example.

use Illuminate\Support\Facades\Crypt;

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

You may decrypt values using the decrypt helper.  See the below example.

use Illuminate\Contracts\Encryption\DecryptException;

try {
    $decrypted = decrypt($encryptedValue);
} catch (DecryptException $e) {
    //
}

Hope it can help you.