AES Encryption with PHP and MySQL

Occasionally, you may find the need to encrypt information within a database. One of the standards for encryption is AES (Advanced Encryption Standard). In fact, in a lot of government institutions, AES is the required data encryption method.

At this point, I feel I need to make an important distinction. Encryption is a reversible method of masking data; not to be confused with hashing, which is supposed to be a one-way encoding method (though, many hash methods can be cracked through various types of attacks).

If you do need to encrypt your data, you have a few options when working with PHP and MySQL.

The first option is a pair of built-in MySQL functions. AES_ENCRYPT() and AES_DECRYPT() make it easy to encrypt and decrypt your data directly through a MySQL query. In order to use the AES_ENCRYPT() and AES_DECRYPT() functions, you will need to provide the data (original data should be provided to the encryption function, the encrypted data should be provided to the decryption function) as the first parameter and a 16-bit key as the second parameter. The same key will need to be used for both functions (otherwise, the decryption won’t work properly).

The second option is to install (if it’s not already installed and configured on your server) the PHP mcrypt extension. You will then want to use the mcrypt_generic() and mdecrypt_generic() functions to encrypt and decrypt the data. Again, if you are using standard AES encryption, you will need to provide a 16-bit key for the data.

In order to use the mcrypt_generic() and mdecrypt_generic() functions, you will need to first open an mcrypt module and initiate it using mcrypt_module_open() and mcrypt_generic_init().

If you want to be able to encrypt/decrypt data interchangeably between PHP and MySQL, you will need to use MCRYPT_RIJNDAEL_128 as the selected cipher and MCRYPT_MODE_ECB as the cipher mode. If you use different values for those items, you will not be able to use the MySQL functions to encrypt/decrypt the data you encrypted/decrypted with PHP.

Did you like this post? Get monthly summary of our new tutorials, posts and tips to your inbox!

No Responses

Post Your Comment

Your email address will not be published.