2011-04-04 103 views
1

我有一段时间试图用md5对PHP进行哈希处理......我尝试移植到PHP的VB代码使用了ComputeHash,它接受一个字节[]并执行整个数组的散列。如何在PHP中模拟computeHash vb函数

Public Shared Function HashBytesMD5(ByVal strInput As String) As Guid 
     Dim oHasher As Cryptography.MD5 = Cryptography.MD5.Create() 
     Dim oEncoder As New System.Text.UTF8Encoding() 
     Dim csData() As Byte 

    csData = oEncoder.GetBytes(strInput) 
    csData = oHasher.ComputeHash(oEncoder.GetBytes(strInput)) 
     Return New Guid(csData) 
    End Function 

现在,我有以下创建一个ascii值的数组。现在我需要md5它像VB.Net一样。它似乎并不像看起来那么直截了当。

$passHash = $this->ConvertToASCII('123456'); 
    $passHash = md5(serialize($passHash)); 


    /* 
    * Converts a string to ascii (byte) array 
    */ 
    function ConvertToASCII($password) 
    { 
     $byteArray = array(); 

     for ($i=0; $i < strlen($password); $i++) { 
      array_push($byteArray,ord(substr($password,$i))); 
     } 

     return $byteArray; 
    } 

注意:在第一个值是字符computeHash MD5之前123456

字节数组

**index**  **Value**     
     [0]   49       
     [1]   50    
     [2]   51    
     [3]   52     
     [4]   53     
     [5]   54 

字节数组从VB computeHash函数返回的ACII值 指数

[0]   225          
[1]   10      
[2]   220     
[3]   57       
[4]   73       
[5]   186      
[6]   89  
[7]   171 
[8]   190 
[9]   86 
[10]   224 
[11]   87 
[12]   242 
[13]   15 
[14]   136 
[15]   62 
+1

在第一次看我不确定这个w应该通过md5'串行化的字节数组来完成。 Sidenote:你使用'substr()'的方式是从'$ i'开始的所有字符串,而我想你只是想要这个单一字符:'substr($ password,$ i,1)' – Fanis 2011-04-04 22:26:33

+0

我得到了php功能来自php手册中的评论。我做了一个print_r,它似乎工作。 – chobo 2011-04-04 22:33:01

+0

nvm你是对的:)好的赶上。 – chobo 2011-04-04 22:47:05

回答

3

我的VB.NET非常生疏,但它看起来像MD5.ComputeHash()的输出可以通过运行你的输入通过md5(),然后把每一对十六进制字符(字节)和转换成十进制重新创建。

$passHash = md5('123456'); 
$strlen = strlen($passHash) ; 

$hashedBytes = array() ; 
$i = 0 ; 
while ($i < $strlen) { 
    $pair = substr($passHash, $i, 2) ; 
    $hashedBytes[] = hexdec($pair) ; 
    $i = $i + 2 ; 
} 
+0

哇,很好的工作!我不认为我会很快得到这一点:)任何机会,你会知道如何将其转换为.NET风格的GUID? – chobo 2011-04-04 23:10:41

4

通过魔法的力量,下面的工作:

function get_VB_hash($text) 
{ 
    $hash = md5($text); 
    $hex = pack('H*', $hash); // Pack as a hex string 
    $int_arr = unpack('C*', $hex); // Unpack as unsigned chars 

    return $int_arr; 
} 

或一条线:

unpack('C*', pack('H*', md5($text)));

证明:

C:\>php -r "print_r(unpack('C*', pack('H*', md5('123456'))));" 
Array 
(
    [1] => 225 
    [2] => 10 
    [3] => 220 
    [4] => 57 
    [5] => 73 
    [6] => 186 
    [7] => 89 
    [8] => 171 
    [9] => 190 
    [10] => 86 
    [11] => 224 
    [12] => 87 
    [13] => 242 
    [14] => 15 
    [15] => 136 
    [16] => 62 
) 
+0

这真是太棒了! – chobo 2011-04-04 23:27:50

+1

更好,性能明智。使用这个,避免我做的循环只显示ComputeHash()所做的事情。 – Fanis 2011-04-05 06:08:19

相关问题