简体   繁体   中英

Make PHP md5 hash match C# hash

I have a code on C# that im trying to rewrite to PHP, when it comes to encription my PHP result doesn't match hash in a DB generated by C# code

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);
    }
  }

Here is a 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==

As shown in code salt is 6ec95f40-9fe3-4014-87d6-40c3b1fff77e pass is Danil18 . DB value maIdHxLbyqD2WkntiLGh2w== , PHP output OTlhMjFkMWYxMmRiY2FhMGY2NWE0OWVkODhiMWExZGI=

Is this code correct and i am missing some text transformation in C# class?

UPDATE: After digging into C# base64 this code still doesnt output same result

        $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==

so, it was kind of hard, but ok:) if you look here there is second param for md5 function.

use it and get the same result:

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

echo base64_encode($string);

output:

maIdHxLbyqD2WkntiLGh2w==

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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