FSO:Encrypt

About

FSO:Encrypt is designed to be a simple generic wrapper for the PHP mcrypt API. It requires both mcrypt (for the encryption) and mhash (for key generation) extensions to be enabled. As far as I know, FSO:Encrypt will support all ciphers and modes that the mhash extension does.

Usage

FSO:Encrypt can be loaded as an FSO module or used standalone. Creating an encryption object is as simple as

<?php
$key = 'some-secret-key';
$cipher = MCRYPT_3DES;
$mode = MCRYPT_MODE_CFB;
$tdes = new Encrypt($key, $cipher, $mode);
//  Encrypt something and display it
echo $tdes->encrypt('blah blah blah');
?>

If you do not specify the cipher or mode, Rijndael-256 (a.k.a. AES-256) will be used in Cipher Block Chaining (CBC) mode by default.

In a lot of cases, you'll probably find that echoing exactly what is output by the encrypt() method results in some unreadable garbage, as your browser/terminal will be trying to interpret the binary data with a character set. Usually you will want to use the encode() and decode() methods instead, which use base64_encode()/base64_decode() to convert the data to a printable format, also suitable for storing in a database text field, etc.

There is also support for encrypting and decrypting entire variables, so for example you can encrypt an array and it will decrypt to the same array. This is achieved using the serialize()/unserialize() built-in functions of PHP. To take advantage of this, use the encode_var()/decode_var() methods.

<?php
$foo = $tdes->encode("this is some text");
printf("Ciphertext is: %s\n", $foo);
printf("Original is: %s\n", $tdes->decode($foo));

$bar = $tdes->encode_var(array("this", "is" => "a", array("multidimensional", "array")));
printf("Ciphertext is: %s\n", $bar);
echo "Original is:\n";
print_r($tdes->decode_var($bar))
?>

The above will give the following output

Note: If you run the above code, the cipher text will not match - this is because a random initialization vector is used for each run of encrypt().

Last modified April 13th, 2008 at 2:50 a.m.