# CakePHP 4 use aes\_encrypt at SQL level

**URL:** <https://discourse.cakephp.org/t/cakephp-4-use-aes-encrypt-at-sql-level/10074>\
**Category:** Need Help\
**Tags:** help\
**Created:** [January 12, 2022, 10:53pm UTC](https://discourse.cakephp.org/t/cakephp-4-use-aes-encrypt-at-sql-level/10074 "2022-01-12T22:53:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gildonei](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/gildonei/32/844_2.png) [@gildonei](https://discourse.cakephp.org/u/gildonei)\
**Post date:** [January 12, 2022, 10:53pm UTC](https://discourse.cakephp.org/t/cakephp-4-use-aes-encrypt-at-sql-level/10074/1 "2022-01-12T22:53:09Z")

</div>

I need to use aes\_encypt(field, key) and aes\_decrypt(field, key) in my project. How can I add it in my table or entity in a way it can works automatic like a virtualField.  
Sample  
$table-\>find([‘fields’ =\> [‘encrypted’]);…

and it get converted to SELECT AES\_DECRYPT(‘encrypted’, ‘key’)…

---

<div class="post-metadata">

**Author:** ![raul338](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/raul338/32/69_2.png) [@raul338](https://discourse.cakephp.org/u/raul338)\
**Post date:** [January 15, 2022, 2:20am UTC](https://discourse.cakephp.org/t/cakephp-4-use-aes-encrypt-at-sql-level/10074/2 "2022-01-15T02:20:15Z")

</div>

create a finder in a table like this

```php
public function findEncrypted(Query $query, array $options): Query
{
    return $query->select([
        'a' => $query->func()->AES_DECRYPT([
            'field_a' => 'identifier',
            'key' => 'literal',
        ]),
    ]);
}

```

You can parametrize it to make it more dynamic.

See [Custom SQL functions](https://book.cakephp.org/4/en/orm/query-builder.html#custom-functions).

---

<div class="post-metadata">

**Author:** ![gildonei](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/gildonei/32/844_2.png) [@gildonei](https://discourse.cakephp.org/u/gildonei)\
**Post date:** [April 20, 2022, 11:13pm UTC](https://discourse.cakephp.org/t/cakephp-4-use-aes-encrypt-at-sql-level/10074/3 "2022-04-20T23:13:54Z")

</div>

I developed a behavior - you can see and download here - [GitHub - gildonei/CakeAes: Encrypt and decrypt fields using AES-256](https://github.com/gildonei/CakeAes)
