Menu

Simple PHP Encryption and Decryption

This is an old post from 2011. As such, it might not be relevant anymore.

The need for encryption and decryption in general day-to-day Web programming is quite rare. But it can crop up from every now and again. I use a class that handles both encryption and decryption using mcrypt and the Rijndael algorithm (AES) and a 256 bit key size.

An important notes to make about encryption (especially this class) is that the output is binary, so you need to make sure if you’re storing it in a database that you use the correct data type, or if you are storing it in a file then give it a correct file extension (alternatively you can just not give it an extension). This is important as storing as, for instance, a .txt will contaminate the cipher text.

<?php
class SimpleEncryption
{
    /**
     * Encrypts a string with a given key.
     *
     * @param string $content
     * @param string $key
     * @return binary
     */
    public function encrypt($content, $key) {
        $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); 
        $iv     = mcrypt_create_iv($ivSize, MCRYPT_RAND); 
        return    mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $content, MCRYPT_MODE_CBC, $iv); 
    }
    
    /**
     * Decrypts a string with a given key.
     *
     * @param binary $content
     * @param string $key
     * @return string
     */
    public function decrypt($content, $key) {
        $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); 
        $iv     = mcrypt_create_iv($ivSize, MCRYPT_RAND); 
        return    mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $content, MCRYPT_MODE_CBC, $iv);
    }
}