Search code examples
phpmcryptblowfish

Substitute Horde/phpmyadmin blowfish.php for mcrypt


I'm trying pass data between applications that was encrypted using the Horde/phpmyadmin blowfish.php library, using mcrypt instead. If I do something like:

$key = "qwerty";
$data = "12345678";

$pma_cipher = new Horde_Cipher_blowfish;

print base64_encode( mcrypt_encrypt( MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC ) );
print PMA_blowfish_encrypt( $data, $key );
print base64_encode( $pma_cipher->encryptBlock( $data, $key ) );
print base64_encode( $pma_cipher->encryptBlock( $data, $key ) );

The output is

pC+XbHWnqIg= // mcrypt
pC+XbHWnqIg= // PMA blowfish
pC+XbHWnqIg= // OK
WwkIWeYzlHw= // next block is different

Furthermore, if I change the data:

$key = "qwerty";
$data = "123456789";

$pma_cipher = new Horde_Cipher_blowfish;

print base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC));
print PMA_blowfish_encrypt( $data, $key );

I now get:

pC+XbHWnqIjaCTiQlKkXRQ==
pC+XbHWnqIg99GXjyWLMmA==

It seems that the Horde/PMA version is changing the key every block.

Is there a way to tweak the mcrypt calls to make the two libraries cross-compatible, or should I just pick one or the other and adjust things accordingly?


Solution

  • The blowfish s-boxes vary by design each time the key is set on the same instance. This is how bcrypt hashing works.

    I believe what you should be doing instead is:

    $pma_cipher = new Horde_Cipher_blowfish;
    
    $pma_cipher->setKey( $key ); // Set the key only once!
    
    print base64_encode( mcrypt_encrypt( MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC ) );
    print PMA_blowfish_encrypt( $data, $key );
    print base64_encode( $pma_cipher->encryptBlock( $data ) ); // specifying the key resets it
    print base64_encode( $pma_cipher->encryptBlock( $data ) ); // specifying the key resets it
    

    This should give you the same result each time.

    In terms of your other question though:

    should I just pick one or the other and adjust things accordingly

    If possible you should use the mcrypt_* functions as they are much faster than the raw PHP implementation used by PMA. Blowfish is notoriously slow (at least in key setup) in the first place; doing that in PHP instead of the C library should only be a fallback.