Home > Backend Development > PHP Tutorial > Blowfish加密,分别使用PHP和C++实现,但结果不同.该如何处理

Blowfish加密,分别使用PHP和C++实现,但结果不同.该如何处理

WBOY
Release: 2016-06-13 12:55:55
Original
742 people have browsed it

Blowfish加密,分别使用PHP和C++实现,但结果不同...
先是MD5实验,结果相同,但使用Blowfish实验,怎么做也成功不了
调用如下:

<?php<br />
     <br />
    $cipher = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_ECB, '');<br />
<br />
    $iv   = '00000000';<br />
    $key  = "strkey11";<br />
<br />
    $stext = '38A0E9312DDA8F7C16B9A12159168C76';<br />
    $stext = md5($stext, true);<br />
    //经过调试知道,在这时$stext的值与C++中MD5后的结果一致<br />
<br />
    if (mcrypt_generic_init($cipher, $key, $iv) != -1)<br />
    {<br />
        $dtext = mcrypt_generic($cipher,$stext );<br />
        mcrypt_generic_deinit($cipher);<br />
<br />
        // Display the result in hex.<br />
        printf("blowfish encrypted:<br>%s<br><br>",strtoupper(bin2hex($dtext)));<br />
    }<br />
    mcrypt_module_close($cipher);<br />
Copy after login

C++的是这样:
    MD5_CTX md5;<br />
    unsigned char str[16];<br />
    md5.MD5String(strSource.c_str() ,str);<br />
<br />
    BlockCipher *bf;<br />
    char key[] = "strkey11";              //Key<br />
    bf = new BlowFish();<br />
    bf->setKey((void *)key, 8*8);<br />
<br />
    bf->encrypt((void *)str, 8);      //unsigned char str[16];<br />
    bf->encrypt((void *)(str+8), 8);<br />
    char temp1[4] = {0};<br />
    char buff1[128] = {0};<br />
    for(int i = 0;i<16;i++)<br />
    {<br />
        sprintf(temp1,"%02x",str[i]);<br />
        strcat(buff1,temp1);<br />
    }<br />
    AnsiString strResult = String(buff1).UpperCase();<br />
    delete bf;
Copy after login

------解决方案--------------------
$iv   = '00000000'; ???
按 bf->setKey((void *)key, 8*8); 理解
应该是
$iv = "\x00\x00\x00\x00\x00\x00\x00\x00";
吧?

------解决方案--------------------
IV is ignored in ECB. IV MUST exist in CFB, CBC, STREAM, nOFB and OFB modes.
MCRYPT_MODE_ECB的模式,$iv是忽略的,应该不是这个问题。

好像是加密之前要padding,你试试看
$size = mcrypt_get_block_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$input = pkcs5_pad($input, $size); 

function pkcs5_pad ($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

function pkcs5_unpad($text)
{
    $pad = ord($text{strlen($text)-1});
    if ($pad > strlen($text)) return false;
    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template