Encryption

Configuration

Before using Lumen’s encrypter, you should set the APP_KEY option of your .env file to a 32 character, random string. If this value is not properly set, all values encrypted by Lumen 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. namespace App\Http\Controllers;
  3. use App\User;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Crypt;
  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' => Crypt::encrypt($request->secret)
  20. ])->save();
  21. }
  22. }

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:

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