Tag Archives: Decrypt

Encrypt & Decrypt CakePHP2 Database Fields

In a current project I’ve been working on I needed to encrypt and decrypt database fields such as user phone numbers and email address. While this is not the only security measure you should have in place it’s certainly worth while for sensitive data that you want to provide a little extra obscurity for. Remember that this trick just encrypts the data so that means that it can be decrypted, in other words a determined hacker could still decode this information if he also gain access to the Security Salt.

You need to add two callback methods to your AppModel.php file. The first is a beforeSave which will encrypt the data before it’s saved and the second is an afterFind function that will decrypt the data after it’s retrieved from the database.

Include the following functions between this code in your AppModel.php file.

beforeSave Function

afterFind Function

The above examples show email, mobile_number, home_number etc being encrypted/decrypted however you could change this for any field you wish. I have also wrapped the encrypt/decrypt code in an if statement to check if there is any data or not as I was finding that even if the field was empty it would still encrypt a “blank” into the database. So for the sake of performance I figured it was best to only encrypt or decrypt when there was real data and not empty fields.

Another thing to be aware of is to change your database fields to VARCHAR(255) otherwise if your field is shorter the encryption hash will get trimmed and will not decrypt properly. I’m also using the CakePHP Security.salt found in the Config/core.php file however you could and probably should use a different generated Security Salt.

Another easy CakePHP tip that works well. Enjoy.