Search code examples
phpblowfishencryption-symmetric

Php Blowfish decryption scrambling data


I am trying to encrypt an xml string, save it somewhere, and then decrypt it later (using blowfish in cbc mode).

When I decrypt the string, it scrambles the first 4 characters.

$text = "<?xml version="1.0" encoding="ISO-8859-1"?> ....";
$td = mcrypt_module_open('blowfish', '', 'cbc', '');
$iv = 'kd84h28v';
$ks = mcrypt_enc_get_key_size($td);
$key = substr(md5('randomString1234'), 0, $ks);
mcrypt_generic_init($td, $key, $iv);
$cypher = mcrypt_generic($td, $text);
print mdecrypt_generic($td, $cypher);

# prints: çGÖºÌrsion="1.0" encoding="ISO-8859-1"?>

I would use ecb mode instead - which decrypts fine - except the current php implementation ignores the iv.

Any ideas what I'm doing wrong?


Solution

  • From the manual:

    It is very important to reinitialize the encryption buffer with mcrypt_generic_init() before you try to decrypt the data.

    So you probably need something like this:

    mcrypt_generic_init($td, $key, $iv);
    $cypher = mcrypt_generic($td, $text);
    mcrypt_generic_deinit($td);
    mcrypt_generic_init($td, $key, $iv);
    print mdecrypt_generic($td, $cypher);