In Depth: Encryption

[InDepth#1] Let's take a look at how Encryption works in Laravel, where it's used, and how you can use it within your applications.

In Depth: Encryption

πŸ‘‰ Looking to dive deeper into Laravel security? Check out Practical Laravel Security, my hands-on security course that uses interactive hacking challenges to teach you about how vulnerabilities work, so you can avoid them in your own code. πŸ•΅οΈ

✨ Worried about your app being hacked? Book in a Laravel Security Audit and Penetration Test! I can find the vulnerabilities before a hacker does, and help you fix them! πŸ•΅οΈ


Laravel provides an encryption service that makes it easy to encrypt and decrypt any serializable1 value that is passed into it using a common key. The encryption key is generated when the application is installed using `php artisan key:generate` and stored in the `.env` file. Laravel uses symmetric encryption with a single key.

It can be used anywhere in your code via the Crypt Facade or via a custom Encrypter instance, and it’s used in a number of places within the Laravel framework itself.

From a quick look, I found these components that use encryption in some way:

  • Cookies
  • Queued jobs
  • CSRF tokens
  • Session storage
  • Eloquent model attribute casting

Encryption vs Hashing & Symmetric vs Asymmetric

Before we go any further, I want to clarify the difference between the terms encryption and hashing, and why Laravel uses symmetric not asymmetric encryption.

  • Encryption is a fully reversable operation where the original value is transformed into an encrypted string using a secret key2. This encrypted string can then be transformed back into the original value with the secret key.

  • Hashing is a one-way operation where the original value is transformed into a hash string via a repeatable algorithm. The hash string cannot be transformed back into the original value, however it can be reproduced if the same original value is hashed again.

A common use of hashing is to store passwords, as it prevents the original password from being retrieved, while allowing you to compare a newly provided password with the original to see if they match.
  • Symmetric encryption uses the same key to both encrypt and decrypt a value. This is what Laravel uses for encryption and what we’ll be covering today.
  • Asymmetric encryption uses different keys, one to encrypt a value and one to decrypt a value, rather than a common key for both. This allows flexibility in how the encryption can be used, as well as verification and integrity checking. It is also known as public-key cryptography, or public-private key.

How The Encrypter Works