Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql and Mcrypt Problem with PHP

Tags:

php

mysql

mcrypt

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?

like image 901
Howard Zoopaloopa Avatar asked Sep 15 '11 18:09

Howard Zoopaloopa


People also ask

What replaces PHP Mcrypt?

ext/mcrypt ¶ The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.

What is Mcrypt PHP extension required?

The mcrypt extension is an interface to the mcrypt cryptography library. This extension is useful for allowing PHP code using mcrypt to run on PHP 7.2+. The mcrypt extension is included in PHP 5.4 through PHP 7.1.

How do I know if Mcrypt is enabled?

You can also achieve this same screen by viewing a php file that has: phpinfo(); somewhere in the code. In this screen, simply search for the string "mcrypt support". If installed, you will see a box that says "enabled".

What is the use of PHP Mcrypt?

What is mcrypt? The mcrypt extension is a replacement for the UNIX crypt command. These commands serve as a means to encrypt files on UNIX and Linux systems. The php-mcrypt extension serves as an interface between PHP and mcrypt.


1 Answers

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.

like image 89
NullUserException Avatar answered Oct 14 '22 00:10

NullUserException