Short encryption and decryption functions in PHP

Occasionally, when writing php tools, you run in to something you’d like encrypted and/or decrypted. You could just use openssl_encrypt, but you’re not using php 5.3, so you have to use mcrypt.

Here’s bit of code I’ve used a few times. Feel free to use it, it comes with absolutely no warranty.


function encryptionKey($username, $password, $ivseed = "!!!") {
    $username = strtolower($username);
    return array(hash("sha1", $password.$username), hash("sha1", $username . $ivseed));
}

function encrypt($data, $key) {
    return
            trim( base64_encode( mcrypt_encrypt(
                    MCRYPT_RIJNDAEL_256,
                    substr($key[0],0,32),
                    $data,
                    MCRYPT_MODE_CBC,
                    substr($key[1],0,32)
            )));
    }

function decrypt($data, $key) {
            return
                    mcrypt_decrypt(
                            MCRYPT_RIJNDAEL_256,
                            substr($key[0],0,32),
                            base64_decode($data),
                            MCRYPT_MODE_CBC,
                            substr($key[1],0,32)
                    );
}

The encryptionKey() function returns an array with two values, the key and the initialization vector. This key is passed with data to the encrypt() and decrypt() functions, which will encrypt and decrypt your data.

encrypt() takes a string for data and your key array and returns the cipher text nicely base64 encoded. decrypt() takes the cipher text and your key array and returns the original string.

If you want compatibility with other encryption and decryption implementations, you probably won’t want to use the encryptionKey() function and just create your own key array. encryptionKey() is really only a utility function to take some data that you’ll have at encryption and decryption time (username, password, constant string) and generate strings of the right length to make the mcrypt functions happy (the mcrypt functions need exactly 32 character strings for key and IV, using the sha1 makes sure they’re long enough).

Example:


$key = encryptionKey($user, $pass, "blahblahblah");
$cipherText = encrypt($plainText, $key);
$decryptedText = decrypt($cipherText, $key);