In various projects in the past I’ve had to revisit the topic of data encryption and decryption and the best way to accomplish it. In the interest of developing in the simplest, most efficient, and most secure way I have chosen the MCrypt PHP library (built-in to PHP since v4.0.2), Rijndael-256 cipher, and the Cipher Block Chaining (CBC) mode.
Previously I have used the Electronic CodeBook (ECB) mode, but have learned that it is far less secure than CBC because it creates the same hash every time for the same source data. CBC on the other hand creates a unique hash every time even for the same source data.
Anyways, below you’ll find my revised encrypt/decrypt functions with support for all PHP data types.
Note: If you are not running PHP 5.3+ then you may need to replace
Update 11/14/2013: Switched to
MCRYPT_DEV_URANDOM. Changed to hexadecimal encryption key that is later converted to binary for use with MCrypt. Added message authentication code (MAC) check. Thanks go to Bryan C. Geraghty for his recommendations.
Update 4/9/2014: Created an object-oriented version for those interested, view the Gist on GitHub.
Update 9/25/2014: Updated decrypt function so that you don’t receive a PHP notice if the input data is formatted incorrectly (not pipe delimited). Thanks go to Jonathan for noticeing.
Update 2/21/2015: Removed references to AES in the article since Rijndael-256 (256-bit blocks & 256-bit keys) is not the same as AES-256 (128-bit blocks & 256-bit keys).