简体   繁体   English

mcrypt_encrypt在PHP 5.6.9上无法正常工作

[英]mcrypt_encrypt not working properly on PHP 5.6.9

I have the following code which worked fine on PHP 5.5.9. 我有以下代码在PHP 5.5.9上运行良好。

function index()
{
    echo $this->encryptText_3des('TEST','JHHKJH9879');
}

function encryptText_3des($plainText, $key) {
    $key = hash("md5", $key, TRUE); 
    for ($x=0;$x<8;$x++) {
        $key = $key.substr($key, $x, 1);
    }
    $padded = $this->pkcs5_pad($plainText,
    mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC));
    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC));
    return $encrypted;
}

function pkcs5_pad ($text, $blocksize)  
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

The encryption was happening fine.But in 5.6.9, the in the PHP doc of mcrypt_encrypt, they mention that 加密发生得很好。但是在5.6.9中,在mcrypt_encrypt的PHP文档中,他们提到了

Invalid key and iv sizes are no longer accepted. 不再接受无效的密钥和iv尺寸。 mcrypt_encrypt() will now throw a warning and return FALSE if the inputs are invalid. mcrypt_encrypt()现在将抛出警告,如果输入无效,则返回FALSE。 Previously keys and IVs were padded with '\\0' bytes to the next valid size. 以前,键和IV用'\\ 0'字节填充到下一个有效大小。

How will I modify my current code with the fifth parameter without altering the encryption algorithm? 如何在不改变加密算法的情况下使用第五个参数修改当前代码?

I tried 我试过了

$iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

and given $iv as fifth parameter. 给$ iv作为第五个参数。

But it didn't work out. 但它没有成功。 The encryption was different from the earlier one. 加密与早期加密不同。

Don't emulate old PHP versions weak behaviour for initializing IV. 不要模拟旧的PHP版本弱行为来初始化IV。

Use mcrypt_create_iv() . 使用mcrypt_create_iv()

They removed the auto zero-byte iv for a reason . 他们删除了自动零字节iv是有原因的

Found the answer in case anyone need 找到答案,以防任何人需要

$ivSize = 8; 
$iv = str_repeat("\0", $ivSize);

$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC, $iv));

Pass a 5th parameter manually which the earlier version was doing on its own! 手动传递第5个参数,这是早期版本自己做的!

I would advise you against reinventing the wheel as your function has numerous cryptography engineering flaws. 我会建议你不要重新发明轮子,因为你的功能有许多加密工程缺陷。

If you're going to use mcrypt (our recommendations for secure data encryption in PHP are to use libsodium if you can; otherwise defuse/php-encryption ; otherwise openssl), make sure you pass the correct constant to mcrypt_create_iv() . 如果您要使用mcrypt(我们在PHP中使用安全数据加密的建议是使用libsodium,如果可以;否则化解/ php-encryption ;否则打开),请确保将正确的常量传递给mcrypt_create_iv()

Bad :

$iv = mcrypt_create_iv(16, MCRYPT_RAND); // BAD EXAMPLE

Good : 好的

$iv = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM); // YES!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM