Encryption

Configuration

Before using Lumens's encrypter, you should set the APP_KEY option of your bootstrap/app.php file to a 32 character, random string. If this value is not properly set, all values encrypted by Lumens 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 Crypt;
  4. use App\User;
  5. use Illuminate\Http\Request;
  6. use App\Http\Controllers\Controller;
  7. class UserController extends Controller
  8. {
  9. /**
  10. * Store a secret message for the user.
  11. *
  12. * @param Request $request
  13. * @param int $id
  14. * @return Response
  15. */
  16. public function storeSecret(Request $request, $id)
  17. {
  18. $user = User::findOrFail($id);
  19. $user->fill([
  20. 'secret' => Crypt::encrypt($request->secret)
  21. ])->save();
  22. }
  23. }

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. }