Encrypt and Decrypt value in Laravel

Encrypt and Decrypt value in Laravel

Editorial Staff
Editorial Staff
22 Dec 2023
1 min read

In this tutorial, we'll explore how to implement encryption and decryption in Laravel, offering a safeguard for your application's crucial data.

Why Encrypt and Decrypt Values?

Before we delve into the how-to, let's understand the importance of encrypting and decrypting values. Encryption transforms this data into a secure format, rendering it unreadable without the proper decryption key. This adds an extra layer of protection against unauthorized access and potential security breaches. 

Note: Encryption should not be an alternate to hashing or storing password.

Encrypt value in Laravel

The first thing that you need is to include Crypt Facade in your Controller or the file you are working on.

use Illuminate\Support\Facades\Crypt;

You should then use encryptString method provided by the Crypt facade to encrypt the text.

Please use the snippet below.

$originalString = "sample";
$encryptedString = Crypt::encryptString($originalString);

echo $encryptedString;  

Ouptut

Something this this

eyJpdiI6IkRCR210cVl0bWV2TmJpR3hnR3RFVHc9PSIsInZhbHVlIjoiS3doOG14UUlrNkhlTEdvQldOM1F2QT09IiwibWFjIjoiNjFkNzFhNjJhOGVkNDczNzNkOWM5YjlhZjZlNjY4NDQwZTk5YzU0MDM3NzJmYjcyMWFjYWQyNTg4MDA5YzI0NiIsInRhZyI6IiJ9

Decrypt value in Laravel

You can decrypt values utilizing the decryptString method provided by the Crypt facade. 

If the value can not be properly decrypted, such as when the message authentication code is invalid, an Illuminate\Contracts\Encryption\DecryptException will be thrown.

use Illuminate\Contracts\Encryption\DecryptException; 
use Illuminate\Support\Facades\Crypt;
 try { 
 	$decryptedValue= Crypt::decryptString($encryptedValue); 
 	echo $decryptedValue;
 } catch (DecryptException $e) { 
 	echo $e->getMessage();
 }

Output

sample

Using Laravel helpers

You may encrypt function as an alternative to the Crypt facade.

$encryptValue = encrypt('your-value');

The decrypt function decrypts the given value. You may use this function as an alternative to the Crypt facade.

$decryptedValue = decrypt($encryptValue);

In this tutorial, we have learnt how encrypt and decrypt values in Laravel to secure sensitive information within your web application.

Editorial Staff

Editorial Staff

Editorial Staff at Code Snipps is a team of experts with over 15+ years of experience in Back-end and Front-end Development especially PHP, MySQL, Laravel, JavaScript, etc. We are your go-to destination for quick and reliable code snippets.