dqy006150 2017-04-23 20:08
浏览 324
已采纳

mcrypt_decrypt返回null响应

I can encrypt strings in php but I cannot decrypt my strings in php when calling the decrypt function, I get a null response. What am I doing wrong? my code is below.

<?php


    $txt = "Hello";
    $mykey = "mysecretkey12345";
    $iv_to_pass_to_decryption = 'mysecretpass23456';





    function encrypt($text, $key)
    {
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND); 
        $iv_to_pass_to_decryption = base64_encode($iv);
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv));

    }


    function decrypt($text, $key, $ivdecrypt)
    { 
        $text = base64_decode($text);
        $ivdecrypt = base64_decode($ivdecrypt);
        return base64_decode(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $ivdecrypt));
    }



    $encryptdata = encrypt($txt, $mykey); // encrypt works fine

    $decryptdata = decrypt($encryptdata, $mykey, $iv_to_pass_to_decryption); // Im getting null response from decrypt

    echo 'Encrypt: ' . $encryptdata . ' Decrypt: ' . $decryptdata;



?>

Example echo output is:

Encrypt: j42DGZVT/cKIWEe5p3289aWGOZCtZ8yN3MuUidi2InM= Decrypt:

  • 写回答

1条回答 默认 最新

  • duankanjian4642 2017-04-23 20:21
    关注

    There are two issues I see: a) The encrypt function assigns the iv to a local variable. You can make it global by including global $iv_to_pass_to_decryption;at the beginning of the encrypt function.

    b) In the return statement of the decrypt function you base_decode the message. But you don't encode it going in. Just remove the base64_decode after return.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器