Encrypt and Decrypt a String in Laravel

Published on September 17, 2021 24 sec read

Laravel’s encryption services provide a simple, convenient interface for encrypting and decrypting text via OpenSSL using AES-256 and AES-128 encryption.

Table of Contents

  1. Encrypt
  2. Decrypt

Encrypt

We can encrypt a value using the encryptString method provided by the Crypt facade. All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher.

use Illuminate\Support\Facades\Crypt;

$encrypted = Crypt::encryptString("Hello World");
dd($encrypted);

Output:

eyJpdiI6Ik1RVW9vUi9qWVcrNVZYVHZLUjB2Tnc9PSIsInZhbHVlI...

Decrypt

We can decrypt values using the decryptString method provided by the Crypt facade.

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;

try {
  $decrypted = Crypt::decryptString("encrypted-string");
  dd($decrypted);
} catch (DecryptException $e) {
  dd($e->getMessage());
}
That’s all. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.

Follow