1

Is this a good implementation of the new PHP mcrypt_generic

private function Encrypt_Decrypt($key, $message, $encrypt = true)
{
    if (!isset($key) || !isset($message))
    {
        throw new Exception("Invalid Parameters");
    }

    $iv = md5(md5($key));
    $output = "";
    $td = mcrypt_module_open("blowfish", "", "cbc", "");

    mcrypt_generic_init($td, $key, $iv);
    switch ($encrypt)
    {
        case true:{
            $output = mcrypt_generic($td, $message);
            break;
        }

        case false:{
            $output = mdecrypt_generic($td, $message);
            break;
        }
    }
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    return $output;
}
Daniel Eugen
  • 2,712
  • 8
  • 33
  • 56
  • If you're using Mcrypt this way you may as well use `mcrypt_encrypt()` and `mcrypt_decrypt()` directly; also, you shouldn't really use `MCRYPT_RAND`. – Ja͢ck Jul 07 '14 at 05:35
  • See also [this answer](http://stackoverflow.com/questions/11051845/php-mcrypt-how-secure-is-it-really/11053755#11053755) and [this one](http://stackoverflow.com/questions/10916284/how-to-encrypt-decrypt-data-in-php/10945097#10945097). – Ja͢ck Jul 07 '14 at 05:36
  • 1
    It's considered better to have both functions separate; merging two opposite flows into the same function kinda smells. – Ja͢ck Jul 07 '14 at 05:42
  • Also, the IV should not be dependent on the used key. – Ja͢ck Jul 07 '14 at 05:44
  • @Jack so how could i handle the iv when i attempt to decrypt a message ? giving that it was a random one... this means that once i encrypt a message i will not be able to decrypt it due to lost iv – Daniel Eugen Jul 07 '14 at 05:45
  • The encrypted message should be accompanied by the used IV; it's like the salt that was used during encryption. – Ja͢ck Jul 07 '14 at 05:47
  • @Jack: can you throw an answer with an edited version of my method showing how could i accomplish what you are referring to ? – Daniel Eugen Jul 07 '14 at 05:48
  • You can have a look at [this answer](http://stackoverflow.com/a/10945097/1338292) as mentioned in my earlier comment; it should give you an idea of how to do it. – Ja͢ck Jul 07 '14 at 05:51

0 Answers0