Published under Laravel.
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.
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
php artisan key:generate
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
Remember that if you dump the model without accessing the property, the value will be output as encrypted.
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
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.
Subscribe to my newsletter to know when I publish more content in the future.