Encrypt and Decrypt Eloquent Model Fields in Laravel Apps
Published on by Paul Redmond
Laravel Ciphersweet is a package by Spatie to integrate searchable field-level encryption in Laravel applications. The package's readme explains the problem Ciphersweet can help solve as follows:
In your project, you might store sensitive personal data in your database. Should an unauthorised person get access to your DB, all sensitive can be read which is obviously not good.
To solve this problem, you can encrypt the personal data. This way, unauthorized persons cannot read it, but your application can still decrypt it when you need to display or work with the data.
This package is a wrapper for Ciphersweet to integrate its features into Laravel models easily. Here's an example of a model from the readme's setup instructions that illustrates what a model looks like using Ciphersweet:
use Spatie\LaravelCipherSweet\Contracts\CipherSweetEncrypted;use Spatie\LaravelCipherSweet\Concerns\UsesCipherSweet;use ParagonIE\CipherSweet\EncryptedRow;use Illuminate\Database\Eloquent\Model; class User extends Model implements CipherSweetEncrypted{ use UsesCipherSweet; public static function configureCipherSweet(EncryptedRow $encryptedRow): void { $encryptedRow ->addField('email') ->addBlindIndex('email', new BlindIndex('email_index')); }}
This allows you the encrypt a user's email to keep it safe from unauthorized people reading the data, but give you the ability to decrypt the data to display it or work with it.
Once you have configured this package and set up a model, you can search encrypted data in the database using blind indexes:
$user = User::whereBlind('email', 'email_index', 'rias@spatie.be');
This package also aids in generating encrypting keys and encrypting model attributes to speed up integration with Ciphersweet.
I want to point out that you should not use this package blindly without understanding the ins and outs of the use case you are trying to solve. You can learn more about CipherSweet on this page, which has many linked resources.
CipherSweet also has PHP-specific documentation to help get you up to speed with the underlying PHP package.
I would also recommend reading Rias' post, Encrypting Laravel Eloquent models with CipherSweet.
To get started with this package, check it out on GitHub at spatie/laravel-ciphersweet.