代码之家  ›  专栏  ›  技术社区  ›  Jhonny D. Cano -Leftware-

php md5算法,其结果与c相同#

  •  7
  • Jhonny D. Cano -Leftware-  · 技术社区  · 16 年前

    我有一个C的哈希算法,简而言之,它是:

    string input = "asd";
    
    System.Security.Cryptography.MD5 alg = System.Security.Cryptography.MD5.Create();
    System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
    
    
    byte[] hash = alg.ComputeHash(enc.GetBytes(input));
    string output = Convert.ToBase64String(hash);
    
    // outputs:   eBVpbsvxyW5olLd5RW0zDg==
    Console.WriteLine(output);
    

    现在我需要在PHP中复制这种行为,

    $input = "asd";
    $output = HashSomething($input);
    echo $output;
    

    我怎样才能做到?

    我检查过了

    • MD5
    • UTF8L译码
    • UTF8L编码
    • Base64编码
    • BASIC 64解码
    • URLL译码

    但是我注意到php md5最后没有得到==我错过了什么?

    注释 :我无法更改C行为,因为它已经实现,并且密码用此算法保存在我的数据库中。

    6 回复  |  直到 13 年前
        1
  •  19
  •   John Downey    16 年前

    问题是PHP的 md5() 函数默认返回哈希的十六进制变化,其中C返回原始字节输出,然后必须使用base64编码使其成为文本安全的。如果运行php5,可以使用 base64_encode(md5('asd', true)) . 注意第二个参数 Md5() 是真的 Md5() 返回原始字节而不是十六进制。

        2
  •  5
  •   Factor Mystic    16 年前

    你记得用php对md5散列进行base64编码吗?

    $result = base64_encode(md5($password, true));

    第二个参数使MD5返回原始输出,这与在C中使用的函数相同。#

        3
  •  4
  •   driis    16 年前

    C代码从字符串中获取utf8字节;计算MD5并存储为base64编码。所以在PHP中也应该这样做,应该是:

    $hashValue = base64_encode(md5(utf8_decode($inputString)))
    
        4
  •  1
  •   Juan Mellado user183856    13 年前

    对于php应该如下所示

     php -r "echo base64_encode(md5(utf8_encode('asd'),true));"
    
        5
  •  0
  •   RRG    15 年前

    我也有同样的问题……只使用MD5(myvar)就行了。我得到了同样的结果c和php。

        6
  •  -1
  •   shanethehat    13 年前

    加文·肯德尔发帖帮助了我。我希望这能帮助别人。

    http://jachman.wordpress.com/2006/06/06/md5-hash-keys-with-c/

    public static string MD5Hash(string text)
    {
        System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(text))), “-”, “”);
    }