Encrypt/decrypt fields - getter always returning null

Preface by saying I don’t really know what I’m doing; but I am messing around with the Security::encrypt() utility to try and get my app to encrypt some data at rest.

I got this far and it seems to be posting the data to the DB as encrypted strings -

 class Contact extends Entity
 {
   
    protected $_accessible = [
        'name' => true,
        'email' => true,
        'phone_number' => true,
        'created' => true,
        'modified' => true,
    ];

    protected function _setEmail(string $email) : string|null
    {
        if (strlen($email) > 0) {
            return Security::encrypt($email, Configure::read('Security.encryptionKey'));
        }
    }

}

this appears to be working OK as my DB is saving the fields presumably as encrypted strings:

then this is where I’m going wrong; but I [looked at the docs (Entities - 4.x) and based my code on the example code

 protected function _getEmail($email) 
 {
    return Security::decrypt($email, Configure::read('Security.encryptionKey'));
 }

and all this does is return an error saying “The data to decrypt cannot be empty” which is fair enough as sometimes email is blank/null.

So I add a check in the getter to just return “null” if it’s empty; and all I get is null.

if I remove the custom _getEmail() I just get the encrypted strings output.

What am I doing wrong?

The method of how you encrypt and decrypt seems fine as well as how you use the getters and setters.

But are you sure the corresponding database column can actually accept that encrypted data?

What you get out of Security::encrypt() is surely “just” a PHP string but it is recommended to use a blob as a column type for such things. Make sure your DB column supports the data you are trying to write into it.

But you could also make your life way easier and just use a plugin like GitHub - bcrowe/cakephp-encrypted-type: CakePHP 4 plugin that provides application-level database encryption.
:wink:

See GitHub - FriendsOfCake/awesome-cakephp: A curated list of amazingly awesome CakePHP plugins, resources and shiny things. for more awesome CakePHP plugins.

Thank you - hadn’t considered plugins; and my DB schema is a varchar(255) so every possibility this is the cause.

I will take a look at those links - thank you