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 choosen the MCrypt PHP library (built-in to PHP since v4.0.2), Rijndael-256 (AES) 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.