5

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?

2
  • Use a blob/binary field instead. text/varchar fields are subject to character translation, while blobs are passed through verbatim. Commented Sep 15, 2011 at 18:40
  • @Marc S/he is using base64_encode() Commented Sep 15, 2011 at 18:40

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

How would I save that? is that something I can also put in my database?
@Jascha Sure, as long as you remember which IV belongs to which ciphertext.
Ok, So, I'll an add an extra 'binary' field (I presume) to store the IV next to the encrypted data and call upon it to decrypt along with my key that is stored somewhere else...
Yes if you store iv in a different field and call it while decoding it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.