php mcrypt CBC mode encryption/decryption problem

大憨熊 提交于 2019-12-23 12:27:41

问题


I have a problem with CBC mode when I try to encrypt/decrypt some text using php's mcrypt extension. I've created a class to perform this operations, it works fine with other modes but CBC.

The problem is as follow:

I use the clear text Even in cryptography, silence is golden. I do the encryption part, no problem till this point. But each time I try to decrypt, I get something like this: 9��'t"�cryptography, silence is golden. As you can see, the first 8 characters of the text are wrong. I don't know what may be causing this behavior.

The parts of my class which handle these operations are:

public function encrypt($data)
    {
        $cypher = $this->_getCypher();
        $iv = $this->_getIv($cypher);

        return trim(base64_encode(mcrypt_encrypt($cypher, self::KEY, $data, MCRYPT_MODE_CBC, $iv)));
    }

    public function decrypt($data)
    {
        $cypher = $this->_getCypher();
        $iv = $this->_getIv($cypher);

        return trim(mcrypt_decrypt($cypher, self::KEY, base64_decode($data), MCRYPT_MODE_CBC, $iv));
    }

    protected function _getCypher()
    {
        return self::$_cyphers[$this->_algorithm];
    }

    protected function _getIv($cypher)
    {
        return mcrypt_create_iv(mcrypt_get_iv_size($cypher, MCRYPT_MODE_CBC), MCRYPT_RAND);
    }

And the algorithm used for above example is 3DES. As I said before, using other mode, such as ECB, everything works fine.

Any suggestions ?


回答1:


You need to remember the IV that you used for encryption and use that again for decryption.



来源:https://stackoverflow.com/questions/6110627/php-mcrypt-cbc-mode-encryption-decryption-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!