How to decrypt using Blowfish algorithm in php?

Sangam254 picture Sangam254 · Apr 7, 2011 · Viewed 23.1k times · Source

I am supposed to write a PHP script to decrypt Blowfish encrypted data.

The data I am receiving for decryption is encrypted by another application (I have no access to it).

The data decrypts fine when am check it using a javascript script (blowfish.js).

How can I decrypt the data in php?

I have tried the mcrypt function in PHP. The code works fine if I encrypt and decrypt using the same code. If I decrypt an encrypted code (in another app) it gives junk.

No idea about what mode to set.

Can anyone suggest on the code below or any PHP BlowFish code without using mcrypt?

<?php

class Encryption
{
    static $cypher = 'blowfish';
    static $mode   = 'cfb';
    static $key    = '12345678';

    public function encrypt($plaintext)
    {
        $td = mcrypt_module_open(self::$cypher, '', self::$mode, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, self::$key, $iv);
        $crypttext = mcrypt_generic($td, $plaintext);
        mcrypt_generic_deinit($td);
        return $iv.$crypttext;
    }

    public function decrypt($crypttext)
    {
        $plaintext = "";
        $td        = mcrypt_module_open(self::$cypher, '', self::$mode, '');
        $ivsize    = mcrypt_enc_get_iv_size($td);
        $iv        = substr($crypttext, 0, $ivsize);
        $crypttext = substr($crypttext, $ivsize);
        if ($iv)
        {
            mcrypt_generic_init($td, self::$key, $iv);
            $plaintext = mdecrypt_generic($td, $crypttext);
        }
        return $plaintext;
    }
}



$encrypted_text = Encryption::encrypt('this text is unencrypted');
 echo "ENCRY=".$encrypted_text;echo "<br/>";

////I am using this part(decryption) coz data already encryption 
// Encrypted text from app 
$encrypted_text = '29636E7ADA7081E7F5D73121C45E20D5';
// Decrypt text
$decrypted_text = Encryption::decrypt($encrypted_text);
  echo "ENCRY=".$decrypted_text;echo "<br/>";

?>

Answer

Jon picture Jon · Apr 7, 2011

The $iv you use when decrypting must be the same as the Initialization Vector used when encrypting the data. Your own functions transfer this information by prepending the IV to the ciphertext (return $iv.$crypttext;), but the other application might not do so.

You need to find out what IV the other app uses, and pass that to your own code. Since the decrypt function reads the IV from the beginning of the ciphertext you can simply prepend it.

Also, you can test a bit by encrypting the same text with your encrypt function and with the other application. If the outputs do not have the same length (your own is larger), then the app is not including the IV inside the ciphertext and you must obtain this information in another manner.

And of course the cipher mode used (CFB) must be the same between your code and the other app.