Search code examples
c#phpencryptionblowfish

Blowfish encryption on C# and PHP yields different results


I'm trying to do a Blowfish encryption, but results in decryption an C#-encrypted code are not the same. I used this library in C#: https://defuse.ca/source/blowfish.cs and this self-written code to encrypt:

$td = MCRYPT_BLOWFISH;
$iv_size = mcrypt_get_iv_size($td, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

echo "Original data: $data<br />"; 

$encrypted_data = mcrypt_encrypt($td, $blowfish_key, $dec, MCRYPT_MODE_CBC, $iv);

echo "Encrypted data: " . bin2hex($encrypted_data)  . "<br />";
$x ="1e9a532f6391071e04ac46dfd4ffa1e324665ef7f1e75b8c2ea6ebabd75fd04d8"; //result from C#
$data = mcrypt_decrypt($td, $blowfish_key, $x /*$encrypted_data*/, MCRYPT_MODE_CBC, $iv);

echo trim($data); 

Could anybody help me with this issue? Thanks in advance. CH


Solution

  • there are 2 problems in your PHP code:

    first: mcrypt expects binary data ... no strings with hex encoded bytes ... (hex2bin() or pack() will convert that for you)

    second: the IV ... your blowfish.cs generates a random IV for you, and puts that (8 bytes) in front of the cyphertext ... while your php codes generates a new random IV which will not work for decryption

    suggestion:

    c#

    var fish = new BlowFish("0000000000000000");
    var cs_output=fish.Encrypt_CBC("This is a test of the blowfish.cs file");
    

    php

    $cs_output="27c7c634ead1d28bfe64821a28ef909311e1f655150f24eec27abff1376a7a8712e7962fdbb0150bfc0882078cb99e67";
    
    $iv=pack("H*" , substr($cs_output,0,16));
    $blowfish_key=pack("H*" , "0000000000000000"); // key in this example is all zero
    $x =pack("H*" , substr($cs_output,16)); 
    $data = mcrypt_decrypt(MCRYPT_BLOWFISH, $blowfish_key, $x , MCRYPT_MODE_CBC, $iv);