Encryption

Introduction

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. All of Laravel's encrypted values are signed using a message authentication code (MAC) so that their underlying value can not be modified once encrypted.

Configuration

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.

Using The Encrypter

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. Furthermore, all encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string:

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

Encrypting Without Serialization

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. If you would like to encrypt and decrypt values without serialization, you may use the encryptString and decryptString methods of the Crypt facade:

  1. use Illuminate\Support\Facades\Crypt;
  2. $encrypted = Crypt::encryptString('Hello world.');
  3. $decrypted = Crypt::decryptString($encrypted);

Decrypting A Value

You may decrypt values using the decrypt helper. If the value can not be properly decrypted, such as when the MAC is invalid, an Illuminate\Contracts\Encryption\DecryptException will be thrown:

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