繁体   English   中英

使PHP md5哈希匹配C#哈希

[英]Make PHP md5 hash match C# hash

我在C#上有一个代码试图将其重写为PHP,当涉及到加密时,我的PHP结果与C#代码生成的数据库中的哈希值不匹配

public sealed class MD5Encryption
  {
    [DebuggerNonUserCode]
    public MD5Encryption()
    {
    }

    public static string Encode(string message)
    {
      return Base64.ConvertToBase64(new MD5CryptoServiceProvider().ComputeHash(new UTF8Encoding().GetBytes(message)));
    }

    public static string EncodeWithSalt(string message, string salt)
    {
      return MD5Encryption.Encode(salt + message);
    }
  }

这是一个C#ConvertToBase64

    public static string ConvertToBase64(byte[] inputBytes)
    {
      return Convert.ToBase64String(inputBytes, 0, inputBytes.Length);
    }
        $string='6ec95f40-9fe3-4014-87d6-40c3b1fff77e'.'Danil18';
        $strUtf8 = mb_convert_encoding($string, "UTF-8");
        $encoded=md5($strUtf8);
        $value=unpack('H*', $encoded);

        echo base64_encode($encoded);//doesn't match maIdHxLbyqD2WkntiLGh2w==

如代码所示,salt是6ec95f40-9fe3-4014-87d6-40c3b1fff77e传递是Danil18 DB值maIdHxLbyqD2WkntiLGh2w== ,PHP输出OTlhMjFkMWYxMmRiY2FhMGY2NWE0OWVkODhiMWExZGI=

这段代码正确吗,我在C#类中缺少某些文本转换?

更新:深入C#base64后,此代码仍不会输出相同的结果

        $string='6ec95f40-9fe3-4014-87d6-40c3b1fff77e'.'Danil18'; //doesn't match maIdHxLbyqD2WkntiLGh2w==
        $string='e734cc98-71bd-45ca-b02c-3b0cf020eb6d'.'x160126@nwytg.net'; //KNv0/uYGHDYuSRxvgYdPoQ==
        $strUtf8 = mb_convert_encoding($string, "UTF-8");
        $encoded=md5($strUtf8);
        //$value=unpack('H*', $encoded);
        $value=unpack('C*', $encoded);

        $chars = array_map("chr", $value);
        $bin = join($chars);
        $hex = bin2hex($bin);

        //$bin = hex2bin($value);
        //print_r($value);
        echo base64_encode($hex);//doesn't match maIdHxLbyqD2WkntiLGh2w== , KNv0/uYGHDYuSRxvgYdPoQ==

因此,这有点困难,但是可以:)如果您在这里看到md5函数的第二个参数。

使用它并获得相同的结果:

<?php
$string = '6ec95f40-9fe3-4014-87d6-40c3b1fff77e'.'Danil18';
$string = utf8_encode($string);
$string = md5($string, true);

echo base64_encode($string);

输出:

maIdHxLbyqD2WkntiLGh2w==

演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM