Menu

MariaDB AES_ENCRYPT() Function

Learn MariaDB AES_ENCRYPT() syntax, binary output, initialization vectors, encryption modes, and safe key-handling limits.

Posted on By Updated on
On this page

MariaDB AES_ENCRYPT() encrypts a string with AES and returns binary data. The matching AES_DECRYPT() function can recover the input when given the same key and encryption parameters. See the official AES_ENCRYPT() documentation.

All key and initialization-vector values below are demonstration placeholders. Do not use them for real data or hard-code production keys in SQL, source code, or the database that holds the ciphertext. MariaDB recommends generating encryption keys with RANDOM_BYTES() and managing keys separately from encrypted data.

Syntax

MariaDB 11.2 and later:

AES_ENCRYPT(str, key [, iv [, mode]])

Earlier versions use the two-argument form:

AES_ENCRYPT(str, key_str)

The optional mode and initialization vector are available starting with MariaDB 11.2. If you omit the mode, MariaDB uses the session’s block_encryption_mode setting. Check that setting before interpreting ciphertext or comparing output across servers.

Examples

Encrypt sample text. HEX() makes the returned binary string easier to display:

SELECT HEX(AES_ENCRYPT('sample text', 'demo-only-key')) AS ciphertext;

On MariaDB 11.2 and later, an explicit IV and mode can be supplied:

SELECT HEX(
    AES_ENCRYPT(
        'sample text',
        'demo-only-key',
        '0123456789abcdef',
        'aes-256-cbc'
    )
) AS ciphertext;

The literal IV above is for demonstration only. Follow the selected mode’s IV requirements in production; do not reuse a fixed example value.

If either the input string or key is NULL, AES_ENCRYPT() returns NULL. The function returns binary data, so use an appropriate binary column such as BLOB when storing ciphertext.

Security limits

AES_ENCRYPT() performs encryption but does not manage keys for your application. Keep keys outside the table containing ciphertext and use a key-management system appropriate for your deployment. Also, encryption alone does not prove that ciphertext has not been altered; do not treat decryption success as an integrity check.

Use password hashing, not reversible encryption, for login passwords. See the OWASP Password Storage Cheat Sheet.

AES_DECRYPT() decrypts the binary output when the same key, IV, and mode are supplied.