tags:

views:

362

answers:

2

I have no idea what I'm doing wrong. I just need to be able to encrypt and decrypt without getting weird characters or warnings. It says I'm supposed to be using an IV of length 16 and that I'm using a length of 9 but "0123456789abcdef" is 16 characters.

Warning: mcrypt_generic_init() [function.mcrypt-generic-init]: Iv size incorrect; supplied length: 9, needed: 16 in /home/mcondiff/public_html/projects/enc/enc.php on line 10

See http://www.teamconcept.org/projects/enc/enc.php

I'm lost, confused, a little lightheaded. Here do I go from here? I have to use this encryption and get it working for a project.

<?php

class enc
{
    function encrypt($str, $key) {
     $key = $this->hex2bin($key);

     $td = mcrypt_module_open("rijndael-128", "", "cbc", "fedcba9876543210");

     mcrypt_generic_init($td, $key, CIPHER_IV);
     $encrypted = mcrypt_generic($td, $str);

     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);

     return bin2hex($encrypted);
    }

    function decrypt($code, $key) {
     $key = $this->hex2bin($key);
     $code = $this->hex2bin($code);

     $td = mcrypt_module_open("rijndael-128", "", "cbc", "fedcba9876543210");

     mcrypt_generic_init($td, $key, CIPHER_IV);
     $decrypted = mdecrypt_generic($td, $code);

     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);

     return utf8_encode(trim($decrypted));
    }

    function hex2bin($hexdata) {
     $bindata = "";

     for ($i = 0; $i < strlen($hexdata); $i += 2) {
      $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
     }

     return $bindata;
    }

}

$theEncryption = new enc();
$user = "John Doe";
$email = "[email protected]";
$user = $theEncryption->encrypt($user, "0123456789abcdef");

$email = $theEncryption->encrypt($email, "0123456789abcdef");

echo 'User: '.$user;
echo 'Email: '.$email;

?>

Can somone point me in the right direction or point out what i'm doing wrong?

Thanks

Mike

+2  A: 

CIPHER_IV is probably an undefined constant. PHP raises a "Use of undefined constant" notice and then uses the "constant" as string. The string "CIPHER_IV" is 9 characters long.

VolkerK
+1  A: 

In your php file, do a print of CIPHER_IV and see what it contains.

See http://us2.php.net/mcrypt_generic_init for the specifics

You've probably copy-pasted the code from a blog: googling mcrypt_generic_init CIPHER_IV only gives this post and a blog ;)

The IV is a parameter that you need to specify to the function, not a constant that the first blogger put in misinterpreting the second blogger's article.

At http://propaso.com/blog/?cat=6, they declare these:

$secret_key = "01234567890abcde";
$iv         = "fedcba9876543210";

and then do:

mcrypt_generic_init($td, $secret_key, $iv);

Simply declare your IV to be something, then use it.

mfontani