首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使PHP与C#哈希匹配

使PHP与C#哈希匹配
EN

Stack Overflow用户
提问于 2019-05-23 22:21:32
回答 1查看 225关注 0票数 0

我有一个在C#上的代码,我试图重写成PHP,当涉及到加密时,我的PHP结果与由C#代码生成的DB中的哈希不匹配

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,pass是Danil18。数据库值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==
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-23 23:44:46

所以,这有点难,但是好吧:)如果你看一下here,这里有第二个md5函数的参数。

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

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

echo base64_encode($string);

输出:

maIdHxLbyqD2WkntiLGh2w==

demo

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56277330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档