我在.Net C#中有这个功能,并希望在PHP中也这样做。但我不了解所有C#部分,也不了解我的代码。
public static string getMD5Hash(string input)
{
MD5 mD = new MD5CryptoServiceProvider();
byte[] array = Encoding.UTF8.GetBytes(input);
array = mD.ComputeHash(array);
StringBuilder stringBuilder = new StringBuilder();
int i = 0;
byte[] array2 = array;
int length = array2.Length;
while (i < length)
{
stringBuilder.Append(array2[i].ToString("x2").ToLower());
i++;
}
return stringBuilder.ToString();
}
我找到了一个例子来描述如何从字符串(谁是相同的)创建MD5哈希:http://en.csharp-online.net/Create_a_MD5_Hash_from_a_string
找到了关于String to Byte的SoF帖子:String to byte array in php
所以我在这里做了一些测试:
function getMD5Hash($input){
for($i = 0; $i < strlen($input); $i++){
$char = substr($input,$i,1);
$hex_ary[] = sprintf("%02X", ord($char));}
$TheMD5=md5(implode('',$hex_ary));
for($i = 0; $i < strlen($TheMD5); $i++){
$char = substr($TheMD5,$i,1);
$Sec_hex_ary[] .= sprintf("%02X", ord($char));}
$StringBuilder ='';
$i = 0;
$Thelength = count($Sec_hex_ary);
while ($i < $Thelength)
{
$stringBuilder .= strtolower(sprintf("%02X", ord($Sec_hex_ary[$i])));
$i++;
}
return $stringBuilder;}
所以我理解(我希望很好):
我错了吗?如果是(当然)你可以解释一下吗?
所以它给了我:“echo getMD5Hash('1ca48ad63d48c3adfae0d7af77f27027');”
Print_r($ hex_ary)=
Array
(
[0] => 31
[1] => 63
[2] => 61
[3] => 34
[4] => 38
[5] => 61
[6] => 64
[7] => 36
[8] => 33
[9] => 64
[10] => 34
[11] => 38
[12] => 63
[13] => 33
[14] => 61
[15] => 64
[16] => 66
[17] => 61
[18] => 65
[19] => 30
[20] => 64
[21] => 37
[22] => 61
[23] => 66
[24] => 37
[25] => 37
[26] => 66
[27] => 32
[28] => 37
[29] => 30
[30] => 32
[31] => 37
)
echo $ TheMD5;
=> 418868f1137ea82935bbd235133993cf
的print_r($ Sec_hex_ary);
Array
(
[0] => 34
[1] => 31
[2] => 38
[3] => 38
[4] => 36
[5] => 38
[6] => 66
[7] => 31
[8] => 31
[9] => 33
[10] => 37
[11] => 65
[12] => 61
[13] => 38
[14] => 32
[15] => 39
[16] => 33
[17] => 35
[18] => 62
[19] => 62
[20] => 64
[21] => 32
[22] => 33
[23] => 35
[24] => 31
[25] => 33
[26] => 33
[27] => 39
[28] => 39
[29] => 33
[30] => 63
[31] => 66
)
回声给我:3333333333333633333333363633333333333636363333333333333333333636
你觉得这是对的吗?谢谢你的帮助。答案 0 :(得分:1)
Encoding.UTF8.GetBytes(input)
行;如果不是,请使用iconv
md5
已经返回一个十六进制字符串,无需从原始输出构建一个总而言之,与C#函数相当的PHP可能是:
echo md5($input);
话虽如此,可能会有一些关于C#的错综复杂的内容让我无法改变结果。