Encryption failing
| From: | Ken Kixmoeller -- reply to ken@kixmoeller.com | Date: | Wed, 16 Jan 2008 00:54:13 +0000 |
| Subject: | Encryption failing | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-267341@lists.php.net to get a copy of this message | ||
Hey --- - -
I am in the process of upgrading the encryption technology I am using from (64 bit) blowfish to (256 bit) rijndael.
The code (and some explanations) is below, but the results are, um, unusual, and I can't see what I am doing wrong. For testing, I have a program that generates a random 16-character string, encrypts it to a variable, and decrypts it. Running it in 500 iteration loops, it fails roughly 4% of the time. By "fails" I mean that the original string and the eventual decrypted one don't match.
Anybody able to spot why?
Ken
--------------------------------------
function jagencdecr($text,$EorD,$encpass='') {
// parameters:
// - $text = string to be en/decrypted,
// - $EorD = Encrypt or Decrypt
// - $encpass = key phrase
if (empty($text)) {return "";}
$text = trim($text);
$cypher = mcrypt_module_open('rijndael-256', '', 'ecb', '');
// "ecb" mode produces the above results.
// "ofb" mode produces 100% errors
$size = mcrypt_enc_get_iv_size($cypher);
$phprand = rand(1000,9999);
$iv = mcrypt_create_iv($size,$phprand); // produces the same results as below, platform independent
//$iv = mcrypt_create_iv($size,MCRYPT_RAND); // for Windows
//$iv = mcrypt_create_iv($size,MCRYPT_DEV_RAND); // for 'NIX
$ks = mcrypt_enc_get_key_size($cypher);
/* Create key */
$key = substr(md5($encpass), 0, $ks);
mcrypt_generic_init($cypher,$key,$iv);
if ($EorD == "D") {
$text_out = mdecrypt_generic($cypher,$text);
} else {
$text_out = mcrypt_generic($cypher,$text);
} // endif ($EorD == "D")
mcrypt_generic_deinit($cypher);
mcrypt_module_close($cypher);
return trim($text_out);
} // endfunc jagencdecr Jaguar Ecnrypt/Decrypt