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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容