Howard Zoopaloopa
Howard Zoopaloopa

Reputation: 3822

Mysql and Mcrypt Problem with PHP

I've seen this asked a few times, but not exactly how I'm going to ask it here... Hopefully this is ok with you guys.

Basically I have this script that works fine and will print my result without a hitch:

$algorithm = MCRYPT_BLOWFISH;
$mode = MCRYPT_MODE_CFB;
$iv = mcrypt_create_iv(mcrypt_get_iv_size($algorithm, $mode), MCRYPT_DEV_URANDOM);
$key = 'Wassup';
$data = 'I am a guy';

$enc_data = rtrim(mcrypt_encrypt($algorithm,$key,$data,$mode,$iv));
$plain_text = base64_encode($enc_data);
echo $plain_text . "\n";

// OUTPUTS: 6m3D5qSrfz3w6pKuuybs

$enc_data = base64_decode($plain_text);
$decoded = mcrypt_decrypt($algorithm,$key,$enc_data,$mode,$iv);
echo $decoded;

// OUTPUTS: I am a guy

This is perfect. NOW... instead of just instantly outputting what I put in, I'm trying to store that info in my database to be decrypted later.

I can see the encrypted string fine in my table row: 6m3D5qSrfz3w6pKuuybs. So, I'm sure it's going IN just fine..

and when I query to get it out it looks just the same, but now when I decode and decrypt I get something like: ÝÄ/$ÍñËt05883700

The table field is set up as a VARCHAR (255) utf8_general_ci. Is this where the problem is?

Upvotes: 5

Views: 2547

Answers (1)

NullUserException
NullUserException

Reputation: 85478

Are you sure you are using the same initialization vector (IV) on encryption and decryption?

Note that you need to save the IV as well and use it when you are decrypting. Also don't use rtrim() on the ciphertext.

That being said, you could use a BINARY (or VARBINARY) field to store your ciphertext (and the IV), so you don't need to base64 encode it. It will save you 33% of storage.

Upvotes: 5

Related Questions