Skip to content

WARNING You're browsing the documentation for an old version of Laravel. Consider upgrading your project to Laravel 12.x.

Encryption

Configuration

Before using Laravel's encrypter, you should set the key option of your config/app.php configuration file to a 32 character, random string. If this value is not properly set, all values encrypted by Laravel will be insecure.

Basic Usage

Encrypting A Value

You may encrypt a value using the Crypt facade. All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string.

For example, we may use the encrypt method to encrypt a secret and store it on an Eloquent model:

1<?php
2 
3namespace App\Http\Controllers;
4 
5use Crypt;
6use App\User;
7use Illuminate\Http\Request;
8use App\Http\Controllers\Controller;
9 
10class UserController extends Controller
11{
12 /**
13 * Store a secret message for the user.
14 *
15 * @param Request $request
16 * @param int $id
17 * @return Response
18 */
19 public function storeSecret(Request $request, $id)
20 {
21 $user = User::findOrFail($id);
22 
23 $user->fill([
24 'secret' => Crypt::encrypt($request->secret)
25 ])->save();
26 }
27}

Decrypting A Value

Of course, you may decrypt values using the decrypt method on the Crypt facade. If the value can not be properly decrypted, such as when the MAC is invalid, an Illuminate\Contracts\Encryption\DecryptException will be thrown:

1use Illuminate\Contracts\Encryption\DecryptException;
2 
3try {
4 $decrypted = Crypt::decrypt($encryptedValue);
5} catch (DecryptException $e) {
6 //
7}

Laravel is the most productive way to
build, deploy, and monitor software.