I've been using this to encrypt information and store it in a mysql database, then decrypt it on a webpage. It almost always works properly, but two times it has failed, decrypting only the last half of the string.
I have the encrypted string stored in a varchar(255) field, and the IV in a varchar(50) field. Do I need to change these to blobs?
Is the IV trying to include a return character that won't store in the database? Is it too long? I thought the check-size function should take care of that...
Any ideas?
Is there any way to decrypt a string that's already been stored, or is it too late?
Why would it decrypt only the LAST half of the string?
Thanks!
Here is my encryption code:
#######################
$key = "This is a short key code...";
// Encryption Algorithm
$cipher_alg = MCRYPT_RIJNDAEL_128;
$stringmod = MCRYPT_MODE_ECB;
// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,
$stringmod), MCRYPT_RAND);
$mod = mcrypt_module_open ($cipher_alg,'',$stringmod,'');
$iv_size = mcrypt_enc_get_iv_size($mod);
$iv = mcrypt_create_iv($iv_size,MCRYPT_DEV_RANDOM);
$max_key_size = mcrypt_enc_get_key_size($mod);
$key = substr($key,0,$max_key_size);
mcrypt_generic_init ($mod,$key,$iv);
$encrypted = mcrypt_generic($mod,$string);
mcrypt_generic_deinit ($mod);
mcrypt_module_close ($mod);
#########################
########Encrypt the data
$ccenc = mcrypt_encrypt($cipher_alg,$key,$string, MCRYPT_MODE_CBC, $iv);
$ccencred = $iv;}
##...Insert into db...
########Decrypt the data
$ccunc = trim(mcrypt_decrypt($cipher_alg, $key, $ccenc, MCRYPT_MODE_CBC, $cciv));