首页 > mcrypt如何对已加密的字符串解密?

mcrypt如何对已加密的字符串解密?

我在准备使用mcrypt加密/解密用户密码, 但是我发现一个问题,
下面是代码, 但是根本不能解密~~~

问题出在生成$iv上, 两次的$iv不同导致加密后的字符串无法正常解密。
由于这两个方法一个在注册时调用, 一个在登录时调用, 所以没有办法共享$iv.

这得怎么啊?

我google出来的结果都是使用同一个$iv进行加密/解密的~~~

    private function encryptPassword($password) {
        if ( self::PASSWORD_MAX_LENGTH < strlen($password) ) {
            $password = substr($password, 0, self::PASSWORD_MAX_LENGTH);
        }

        /* @var $accountService AccountService */
        $accountService = X::system()->getServiceManager()->get(AccountService::getServiceName());
        $passwordSecret = $accountService->getConfiguration()->get('password_secret');

        $cipherAlg = MCRYPT_RIJNDAEL_128;
        $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipherAlg,MCRYPT_MODE_ECB), MCRYPT_RAND);
        $encryptedPassword = mcrypt_encrypt($cipherAlg,$passwordSecret,$password, MCRYPT_MODE_CBC, $iv);

        $encryptedPassword = base64_encode($encryptedPassword);
        return $encryptedPassword;
    }

    /**
     * @param unknown $encryptedPassword
     */
    private function decryptPassword($encryptedPassword) {
        /* @var $accountService AccountService */
        $accountService = X::system()->getServiceManager()->get(AccountService::getServiceName());
        $passwordSecret = $accountService->getConfiguration()->get('password_secret');

        $cipherAlg = MCRYPT_RIJNDAEL_128;
        $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipherAlg,MCRYPT_MODE_ECB), MCRYPT_RAND);


        $encryptedPassword = base64_decode($encryptedPassword);
        $decryptPassword = mcrypt_decrypt($cipherAlg, $passwordSecret, $encryptedPassword, MCRYPT_MODE_CBC, $iv);
        return $decryptPassword;
    }

初始化向量iv是不需要每次都重新生成的,你可以保存下来,拿你的场合来说,你可以把它和密文一起存储,这样就可以解决这个问题了。你可以读php的官方文档的解释 http://php.net/manual/zh/function.mcrypt-create-iv.php

【热门文章】
【热门文章】