尝试在 C# 中重现 PHP 的 pack("H*") 函数 [英] Trying to reproduce PHP's pack("H*") function in C#

查看:79
本文介绍了尝试在 C# 中重现 PHP 的 pack("H*") 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 C# 代码:

this is my code in C# :

    public static String MD5Encrypt(String str, Boolean raw_output=false)
    {
        // Use input string to calculate MD5 hash
        String output;
        MD5 md5 = System.Security.Cryptography.MD5.Create();
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(str); 
        byte[] hashBytes = md5.ComputeHash(inputBytes);

        // Convert the byte array to hexadecimal string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        {
            sb.Append(hashBytes[i].ToString("x2"));
        }

        output = sb.ToString();

        if (raw_output)
        {
            output = pack(output);
        }

        return output;
    }

    public static String pack(String S)
    {
        string MultiByte = ""; 

        for (int i = 0; i <= S.Length - 1; i += 2)
        {
            MultiByte += Convert.ToChar(HexToDec(S.Substring(i, 2)));
        }

        return MultiByte;
    }

    private static int HexToDec(String hex)
    {
        //Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
        return Convert.ToInt32(hex, 16);
    }

通过这种方式重现在 php 中所做的事情:

To reproduce what is done in php by this way :

md5($str, true);

pack('H*', md5( $str ));

我尝试了很多东西,但在某些情况下无法在两侧得到相同的结果.例如,在字符串8tv7er5j"上尝试这个测试

I tried many things but can't get the same on the two sides in some cases of word. For example, Trying this test on the string "8tv7er5j"

PHP 端:

9c36ad446f83ca38619e12d9e1b3c39e <= md5("8tv7er5j");
œ6­DoƒÊ8ažÙá³Ãž <= md5("8tv7er5j", true) or pack("H*", md5("8tv7er5j"))

C# 端:

9c36ad446f83ca38619e12d9e1b3c39e <= MD5Encrypt("8tv7er5j")
6­DoÊ8aÙá³Ã <= MD5Encrypt("8tv7er5j", true) or pack( MD5Encrypt("8tv7er5j") )

为什么?编码问题?

编辑 1:我有很好的结果,但用这个函数为 pack() 编码不好:

EDIT 1 : I have the good result, but bad encoded with this this function for pack() :

if ((hex.Length % 2) == 1) hex += '0';

byte[] bytes = new byte[hex.Length / 2];

for (int i = 0; i < hex.Length; i += 2)
{
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}

return bytes;

所以,System.Text.Encoding.UTF8.GetString(bytes) 给我:6 做 8a Þ

So, System.Text.Encoding.UTF8.GetString(bytes) give me : �6�Do��8a���Þ

和 System.Text.Encoding.ASCII.GetString(bytes)?6?做??8a????

And System.Text.Encoding.ASCII.GetString(bytes) ?6?Do??8a??????

...

推荐答案

我遇到了同样的场景,我在 C# 中需要 php 的 pack-unpack-md5 函数.最重要的是,我需要将这 3 个函数与 php 匹配.

I encountered same scenario where I am in need of php's pack-unpack-md5 functions in C#. Most important was that I need to match out of all these 3 functions with php.

我创建了自己的函数,然后使用 onlinephpfunctions.com 上的函数验证(验证)了我的输出.当我用 DefaultEncoding 解析时,输出是一样的.仅供参考,我检查了我的应用程序的编码(Encoding.Default.ToString()),它是 System.Text.SBCSCodePageEncoding

I created my own functions and then validated(verified) my output with functions at onlinephpfunctions.com. The output was same when I parsed with DefaultEncoding. FYI, I checked my application's encoding(Encoding.Default.ToString()) and it was System.Text.SBCSCodePageEncoding

打包

    private static string pack(string input)
{
    //only for H32 & H*
    return Encoding.Default.GetString(FromHex(input));
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}

MD5

    private static string md5(string input)
{
    byte[] asciiBytes = Encoding.Default.GetBytes(input);
    byte[] hashedBytes = MD5CryptoServiceProvider.Create().ComputeHash(asciiBytes);
    string hashedString = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
    return hashedString;
}

开箱

私有静态字符串解包(字符串p1,字符串输入){StringBuilder 输出 = new StringBuilder();

private static string unpack(string p1, string input) { StringBuilder output = new StringBuilder();

    for (int i = 0; i < input.Length; i++)
    {
        string a = Convert.ToInt32(input[i]).ToString("X");
        output.Append(a);
    }

    return output.ToString();
}

PS:用户可以用其他格式增强这些功能

这篇关于尝试在 C# 中重现 PHP 的 pack("H*") 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆