drwxg62286 2012-11-16 23:07
浏览 100
已采纳

PHP中的Blowfish加密

I'm writing an encryption to my application and website, but I don't know how to correctly encrypt the string in php. Decryption is already done by this code:

function decrypt_blowfish($data,$key){
$iv=pack("H*" , substr($data,0,16));
$key=pack("H*" , $key);
$x =pack("H*" , substr($data,16)); 
$res = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $x , MCRYPT_MODE_CBC, $iv);
return $res;
}

I tried with simple:

function encrypt_blowfish($data,$key){
    $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
    return $crypttext;
}

But it returns strang ASCI chars instead of correct blowfish code. Could somebody explain me why, and what am I doing wrong? Thanks in advance

C.H.

  • 写回答

1条回答 默认 最新

  • doushu5451 2012-11-16 23:15
    关注
    function decrypt_blowfish($data,$key){
        $iv=pack("H*" , substr($data,0,16));
        $x =pack("H*" , substr($data,16)); 
        $res = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $x , MCRYPT_MODE_CBC, $iv);
        return $res;
    }
    
    function encrypt_blowfish($data,$key){
        $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $crypttext = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv);
        return bin2hex($iv . $crypttext);
    }
    
    $string = encrypt_blowfish('hello world', 'abc123');
    echo 'ENCRYPTED: ' . $string . "
    ";
    echo 'DECRYPTED: ' . decrypt_blowfish($string, 'abc123');
    

    Try that. In the decryption function you are converting from hex to binary, so it is expecting a hex value to be passed. Your encryption function is outputting binary, so you need to convert it to hex with the above change.

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

报告相同问题?

悬赏问题

  • ¥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设计 源简并电感型共源放大器