Simple Mcrypt Encrypt & Decrypt Functions for PHP

Sometimes you need to encrypt some plain text before sending over an insecure channel.
Here’s a very simple encrypt/decrypt pair of functions using the PHP Mcrypt extension that should be enabled on your Apache server.


    $salt ='secret text shared by both ends';

    function simple_encrypt($text)
    {
        return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
    }

    function simple_decrypt($text)
    {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
    }

7 thoughts on “Simple Mcrypt Encrypt & Decrypt Functions for PHP

Leave a reply to Anonymous Cancel reply