Replace Mcrypt with OpenSSL

放肆的年华 提交于 2019-11-26 05:02:43

Blowfish is the block cipher. It requires the data to be padded before encryption. OpenSSL uses PKCS#7 and mcrypt uses PKCS#5. Different padding algorythms for data. Minimal PKCS#5 padding length is 0, for PKCS#7 it's 1 (wikipedia). Take a look at this example (i've manually padded input data for mcrypt_encrypt() in PKCS#7 style):

<?php 

$key = "anotherpassword1";
$str = "does it work 12";

$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $str."\1", MCRYPT_MODE_ECB);
$dec = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB);
echo(bin2hex($enc).PHP_EOL);
var_dump($dec);

$enc = openssl_encrypt($str, 'bf-ecb', $key, true);
$dec = openssl_decrypt($enc, 'bf-ecb', $key, true);
echo(bin2hex($enc).PHP_EOL);
var_dump($dec);

?>

It's impossible to openssl_decrypt() data encrypted with mcrypt_encrypt(), unless manual data padding was made with PKCS#7 before mcrypt_encrypt() was called.

There is only one way in your case - recrypt the data.

PS: There is an error in your source - ECB mode does not uses IV at all (wikipedia)

In case you want to encrypt with openssl and still get the same result as if you had encrypted it with mcrypt when decrypting with mcrypt, you need to manually null-pad the input string prior to encrypting it with openssl_encrypt and pass the OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING options.

$str = 'encrypt me';
$cipher = 'AES-256-CBC';
$key = '01234567890123456789012345678901';
$opts = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;
$iv_len = 16;
$str_len = mb_strlen($str, '8bit');
$pad_len = $iv_len - ($str_len % $iv_len);
$str .= str_repeat(chr(0), $pad_len);
$iv = openssl_random_pseudo_bytes($iv_len);


$encrypted = openssl_encrypt($str, $cipher, $key, $opts, $iv);

Decrypting with mcrypt_decrypt will then work just as if you had also used mcrypt for encryption.

mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv)

For shorter keys, you should make cycled keys for openssl when migrating mcrypt's blowfish.

function make_openssl_blowfish_key($key)
{
    if("$key" === '')
        return $key;

    $len = (16+2) * 4;
    while(strlen($key) < $len) {
        $key .= $key;
    }
    $key = substr($key, 0, $len);
    return $key;
}

See: https://bugs.php.net/bug.php?id=72362

See: Moving from mcrypt with Blowfish & ECB to OpenSSL

@clover is right that the default padding for Blowfish is different between mcrypt and Openssl, but is wrong that it can't be done. If you use the OPENSSL_ZERO_PADDING option for the decrypt the two actually are compatible:

openssl_decrypt($data, 'bf-ecb', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!