Listing 4. Typical Usage of the Mcrypt Extension

<?php
/* Create your key at random
   but keep it handy as you
   will use it to decrypt later
*/
$key = "AOQKJLCLIGAKJHSD
        <NKLXASLUIHJKHAS
        OIUDSgfuyJKLBLKU";

$string = $_POST['password'];

/* First, you must open the encryption module
   provided by Mcrypt */
$mod = mcrypt_module_open ('blowfish','','ecb','');

/* You must then create an Initialization Vector
   based on a size and a source.
   Your source can be custom, but some constants
   are available.
   Defining the size of the vector depends on the
   module you are using */
$iv_size = mcrypt_enc_get_iv_size($mod);

/* The initialization vector will be based on $size
   characters from the source /dev/random in our
   example */
$iv = mcrypt_create_iv($iv_size,MCRYPT_DEV_RANDOM);

/* The next step is to ensure that your key is not
   too big and truncate it if necessary */
$max_key_size = mcrypt_enc_get_key_size($mod);
$key = substr($key,0,$max_key_size);

/* You must then initialize the encryption
   mechanism through mcrypt_generic_init */
mcrypt_generic_init ($mod,$key,$iv);

/* You can now encrypt your data through
   the use of mcrypt_generic. The function
   will return your encrypted data */
$encrypted = mcrypt_generic($mod,$string);

/* Once you have finished using Mcrypt, you
   must free the buffers used during the process */
mcrypt_generic_deinit ($mod);

/* Finally, you must close the encryption module
   you have used*/
mcrypt_module_close ($mod);

/* Now here is how we can decrypt our data: */
$padded = // see next line
mcrypt_decrypt('blowfish',$key,$encrypted,'ecb',$iv);
/* At this point, our decrypted string has been
   zero-padded so we need to remove the extra \0s */
$plain = str_replace("\0","",$padded);
echo "Encrypted string: $encrypted<br>";
echo "Decrypted string: $plain<br>";
?>

