Search code examples
phpopensslmcrypt

How to use OpenSSL to decrypt a value generated with Mcrypt that has used an ASCII key?


I need to be able to decrypt values using OpenSSL that were generated using Mcrypt under PHP.

I have this working, with the exception that the key used to encrypt them was ascii.

The following is my code that demonstrates a working case where OpenSSL can decrypt the value encrypted with Mcrypt, when the key is an MD5.

<?php
$message = 'test';
$key = md5('Quigibo');

$iv = openssl_random_pseudo_bytes(0);

$encrypted = mcrypt_encrypt(
    MCRYPT_BLOWFISH,
    $key,
    $message,
    MCRYPT_MODE_ECB,
    $iv
);

$decrypted = openssl_decrypt(
    $encrypted,
    'bf-ecb',
    $key,
    OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,
    $iv
);

$trimDecrypted = rtrim($decrypted);

var_export(
    [
        'Original message' => $message,
        'Encrypted' => bin2hex($encrypted),
        'Decrypted' => $decrypted,
        'Trim decrypted' => $trimDecrypted,
        'Message length' => mb_strlen($message, '8bit'),
        'Decrypted length' => mb_strlen($decrypted, '8bit'),
        'Message == decrypted' => $message === $trimDecrypted
    ]
);

However, if you change $key to be the value "Quigibo" (as opposed to an MD5 hash of that value) the encrypted value cannot be decoded with OpenSSL.

Is there a form of encoding I can apply to the ASCII key prior to use with OpenSSL such that it will correctly decrypt the value?


Solution

  • Revised answer:

    There is a bug in OpenSSL which null pads the key to 16 bytes for Blowfish, which is incorrect because the cipher supports a variable length key. They have very recently added a flag to fix this - OPENSSL_DONT_ZERO_PAD_KEY - but it is only available in php 7.1.8 which was released a little over a week ago... Relevant bug: https://bugs.php.net/bug.php?id=72362

    A workaround is to manually cycle the key and feed that into OpenSSL:

    $keylen = (floor(mb_strlen($key, '8bit')/8)+1)*56;
    $key_cycled = substr(str_repeat($key,ceil($keylen/strlen($key))),0,$keylen);
    
    $decrypted = openssl_decrypt(
    $encrypted,
    'bf-ecb',
    $key_cycled,
    OPENSSL_RAW_DATA | OPENSSL_NO_PADDING,
    $iv
    );