Encryption - Laravel
Encryption - Laravel
SEARCH 5.2
Encryption
# Configuration
# Basic Usage
# 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
AES256CBC 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:
<?php
namespaceApp\Http\Controllers;
useCrypt;
useApp\User;
useIlluminate\Http\Request;
useApp\Http\Controllers\Controller;
classUserControllerextendsController
/**
https://laravel.com/docs/5.2/encryption 1/3
2017516 EncryptionLaravelThePHPFrameworkForWebArtisans
/**
*Storeasecretmessagefortheuser.
*@paramRequest$request
*@paramint$id
*@returnResponse
*/
publicfunctionstoreSecret(Request$request,$id)
$user=User::findOrFail($id);
$user>fill([
'secret'=>Crypt::encrypt($request>secret)
])>save();
Note: Encrypted values are passed through serialize during encryption, which allows for "encryption" of
objects and arrays. Thus, non-PHP clients receiving encrypted values will need to unserialize the data.
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:
useIlluminate\Contracts\Encryption\DecryptException;
try{
$decrypted=Crypt::decrypt($encryptedValue);
}catch(DecryptException$e){
//
L A R A V E L I S A T R A D E M A R K O F T AY L O R O T W E L L . C O P Y R I G H T T AY L O R O T W E L L .
DESIGNED BY
https://laravel.com/docs/5.2/encryption 2/3
2017516 EncryptionLaravelThePHPFrameworkForWebArtisans
https://laravel.com/docs/5.2/encryption 3/3