Erik
Erik

Reputation: 630

Php encrypt not working

Does anyone know why this php encrypt/decrypt is not working?
We used this in our website, and it worked mostly. But now we made it a command line script, and it stopped working at all...

We tried encoding the key to utf8 and tried to remove the trim. But both are not working.

$e = new enc();
$pass = !isset($argv[1]) ? 'ill' : $argv[1];
$encPass = $e->_encrypt($pass);
$decPass = $e->_decrypt($encPass);

echo 'input: '. $pass . "\n";
echo 'encode: ' . $encPass . "\n";
echo 'decode: ' . $decPass;

class enc
{
/**
     * Encrypt data using AES256
     *
     * @param string $data The plaintext
     * @return string The encyrypted data
     */
    function _encrypt($data)
    {
        $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        return mcrypt_encrypt(
            MCRYPT_RIJNDAEL_256, "gw2iYt26Gw", trim($data), MCRYPT_MODE_ECB,
            $iv
        );
    }

    /**
     * Decrypt data using AES256
     *
     * @param string $data The AES256 encrypted data
     * @return string The decyrypted data
     */
    function _decrypt($data)
    {
        $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        return trim(
            mcrypt_decrypt(
                MCRYPT_RIJNDAEL_256, "gw2iYt26Gw", trim($data),
                MCRYPT_MODE_ECB, $iv
            )
        );
    }
}
?>

EDIT: Little fix for using encPass to decrypt

Upvotes: 1

Views: 969

Answers (2)

Linus Kleen
Linus Kleen

Reputation: 34632

You're decrypting the plain password.

Do:

$decPass = $e->_decrypt($encPass);

EDIT after question update: You'll have to remove the call to trim() when decoding. It messes up your input. Weed out the trimming in enc::_decrypt() and it works.

Upvotes: 2

Sjoerd
Sjoerd

Reputation: 75599

The CLI version of PHP may have a different config than the Apache version. That means that if your Apache version has mcrypt support, it does not mean that the CLI version has mcrypt support. Check with php -i.

Upvotes: 0

Related Questions