php mcrypt CBC模式加密/解密问题 [英] php mcrypt CBC mode encryption/decryption problem

查看:369
本文介绍了php mcrypt CBC模式加密/解密问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CBC模式的问题,当我尝试使用php的mcrypt扩展加密/解密一些文本。我创建了一个类来执行这个操作,它适用于其他模式,但CBC。

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.

问题如下:

我使用明文即使在加密中,沉默也是金色的。我做加密部分,没有问题,直到这一点。但是每次我尝试解密,我得到这样的:9 't 加密,沉默是金。正如你可以看到,前8个字符

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);
    }

上面例子中使用的算法是3DES。正如我之前说的,使用其他模式,如ECB,一切工作正常。

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

有任何建议吗?

推荐答案

您需要记住用于加密的IV,并再次使用它进行解密。

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

这篇关于php mcrypt CBC模式加密/解密问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆