I am trying to encrypt sensitive user data like personal messages in my php powered website before entering into the database. I have researched a bit on the internet and I have found the few important things to remember:
Never use mcrypt, it’s abandonware.
AES is based on the Rijndael algorithm and has been unbroken till now.
AES has also been recommended by NSA and used in US Government data encryption, but since the NSA is recommending it, there’s a chance they might sneak upon my user data easily.
Blowfish has been unbroken as well, but slow and less popular.
So, I decided I will give it a try first with AES-256 cbc. But I am still not sure if I should not consider Blowfish a better option. So any recommendations are welcome.
And my primary concern is, how to encrypt the data in php? I don’t find a good manual about this in the php documentation. What is the correct way to implement it?
Any help is heavily appreciated.
AES-256 (OpenSSL Implementation)
You’re in Luck.
openssl extension has some pretty easy to use methods for AES-256. The steps you need to take are basically…
- Generate a 256-bit encryption key (This needs storing somewhere)
$encryption_key = openssl_random_pseudo_bytes(32);
- Generate an “initialization vector” (This too needs storing for decryption but we can append it to the encrypted data)
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
- encrypt data using
openssl_encrypt($data, 'aes-256-cbc', $encryptionKey, $options, $initializationVector)
$optionscan be set to
0for default options or changed to
OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING
- append the initialisation vector to the encrypted data
$encrypted = $encrypted . ':' . $iv;
- retrieve the encrypted data and the initialization vector.
explode(':' , $encrypted);
- decrypt data using
openssl_decrypt($encryptedData, 'aes-256-cbc', $encryptionKey, $options, $initializationVector)
openssl_functions() won’t be available by default, you can enable this extension in your
php.ini file by uncommenting the line.
;extension=php_openssl.dll by removing the leading