Storing and testing encrypted values in Laravel

Published under Laravel.

📺  Click here to skip to the video attached to this post  👇

When writing web applications, there are times where you'll need to store an encrypted value in the database. One example might be a secret token that you want extra security around in case your data is exposed. Furthermore, once you've stored the encrypted values, you'll probably want to test that they're actually stored encrypted instead of in plaintext.

Storing encrypted values

There's an open source package available written by Jeff Sagal, which will automatically encrypt values for specified database columns: Encryptable. Let's run through how you can use it.

Install the composer package:

  • composer require sagalbot/encryptable

Ensure you have an application key generated, skip this if you already have a key set in your .env file:

  • php artisan key:generate

Add the Encryptable trait to the model you want to encrypt a column on, and then add an $encryptable array to the model with the list of columns you want to store encrypted:

Now whenever your model is saved with a secret_token value set, the secret_token value will be encrypted before being written to the database. When pulling the model from the database, the encrypted value will only be decrypted when either the property is accessed directly or through a toArray or toJson function.

Remember that if you dump the model without accessing the property, the value will be output as encrypted.

Testing encrypted values

Now that we have our value stored encrypted, we can write a test to confirm its stored encrypted and not in plaintext.

For this, we're going to use a package I wrote called Laravel Assert Encrypted. This package exposes a new assertion method for your tests to assert a database has an encrypted value in a specified column.

First, install the package:

  • composer require ohseesoftware/laravel-assert-encrypted

Add the AssertEncrypted trait from the package to your test class:

Use the new assertEncrypted method to test your encrypted value:

The first argument is the table to query against, the second argument is the where data that should be used to find the row in the table, and the third argument is the encrypted data you're expecting.

Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0