Search code examples
phpmcrypt

PHP mycrypt problem, weird characters/warnings


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 = "john@example.com";
$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


Solution

  • 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.