Decrypting Blowfish Encrypted HEX String in PHP

I had need recently to use PHP to decrypt some short strings that were encrypted using the Blowfish algorithm. They were encrypted to HEX strings which necessitated converting them to strings. An added complication was that the mcrypt library in PHP is deprecated from version 7.3 onward and this code needs to function beyond that point. A couple of things to note are that the openssl_decrypt call requires a 16 byte key even though it only uses the first 8 bytes, the mcrypt_decrypt call also only uses the first 8 bytes of the key (but can also be safely passed an 8 byte key). Also you can see that RTRIM is used to get rid of any trailing \0 (NULL) or \4 (EOT) chars. It’s not unusual for there to be trailing characters as the encryption process pads out the text to be encrypted to a number of bytes that is evenly divisible by the encryption key. The data I’m decrypting here was originally encoded in an old VB6 application which padded out the string to be encrypted with EOT characters.

The key shown in this code is NOT the key used to create the encoded HEX string as I’m keeping the actual key secret because it’s used in some commercial software.

<?php
$encrypted_string = hexToStr("7363284E8E3FEA58");
echo "encrypted string:: ".$encrypted_string . "<br />";
echo "decrypted string:: ".decrypt_blowfish_string($encrypted_string,0);

function hexToStr($hex) {
    $str = '';
    for ($i = 0; $i < strlen($hex); $i += 2){
        $str .= chr(hexdec(substr($hex, $i, 2)));
    }
    return $str;
}

function decrypt_blowfish_string($string, $force_openssl = 0) {
    $key = 'somekey';
    $key_length = strlen($key);
    if ($key_length < 16) {
        $key = str_repeat($key, ceil(16 / $key_length));
    }
    if (function_exists('mcrypt_encrypt') && $force_openssl==0) {
        $plaintext = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $string, MCRYPT_MODE_ECB);
    } else {
        $plaintext = openssl_decrypt($string, 'BF-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
    }
    return rtrim($plaintext, "\0\4");
}
?>
This entry was posted in php on by .

About markn

Mark is the owner and founder of Timesheets MTS Software, an mISV that develops and markets employee timesheet and time clock software. He's also a mechanical engineer, father of four, and a lifelong lover of gadgets.