I have taken some time to see how mcrypt() works, and have produced two functions that seem to work quite well.
I chose CAST-256..
/*
Exerpt from CAST-256 encryption algorithm documentation:
This document describes the CAST-256 encryption algorithm, a DES-like
Substitution-Permutation Network (SPN) cryptosystem built upon the
CAST-128 encryption algorithm [1] which appears to have good
resistance to differential cryptanalysis, linear cryptanalysis, and
related-key cryptanalysis. This cipher also possesses a number of
other desirable cryptographic properties, including avalanche, Strict
Avalanche Criterion (SAC), Bit Independence Criterion (BIC), no
complementation property, and an absence of weak and semi-weak keys.
It thus appears to be a good candidate for general-purpose use
throughout the Internet community wherever a cryptographically-
strong, freely-available encryption algorithm is required.
CAST-256 has a block size of 128 bits and a variable key size (128,
160, 192, 224, or 256 bits).
*/
and the encrypt/decrypt functions:
**note: I am using base64 encoding so that the strings will save pretty in databases/files/html-to-browser. If you don't need it, remove it 🙂
function encrypt($key, $plain_text) {
// returns encrypted text
// incoming: should be the $key that was encrypt
// with and the $plain_text that wants to be encrypted
$plain_text = trim($plain_text);
/* Quoting Mcrypt:
"You must (in CFB and OFB mode) or can (in CBC mode)
supply an initialization vector (IV) to the respective
cipher function. The IV must be unique and must be the
same when decrypting/encrypting."
Meaning, we need a way to generate a _unique_ initialization vector
but at the same time, be able to know how to gather our IV at both
encrypt/decrypt stage. My personal recommendation would be
(if you are working with files) is to get the md5() of the file.
In this example, however, I want more of a broader scope, so I chose
to md5() the key, which should be the same both times. Note that the IV
needs to be the size of our algorithm, hence us using substr.
*/
$iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CF😎);
$c_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $plain_text, MCRYPT_ENCRYPT, $iv);
return trim(chop(base64_encode($c_t)));
}
function decrypt($key, $c_t) {
// incoming: should be the $key that you encrypted
// with and the $c_t (encrypted text)
// returns plain text
// decode it first 🙂
$c_t = trim(chop(base64_decode($c_t)));
$iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CF😎);
$p_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $c_t, MCRYPT_DECRYPT, $iv);
return trim(chop($p_t));
}
cheers,
kyle