JavaScript中MD5.hex()的.NET等效方法

4

我正在尝试连接一个使用MD5.hex(密码)加密密码后再将其发送到PHP的带有身份验证的网站。 如何在C#中实现相同的加密?

编辑1:

Javascript(YUI库):

pw = MD5.hex(pw);
this.chap.value = MD5.hex(pw + this.token.value); 

C#.NET

string pw = getMD5(getHex(getMD5(getHex(my_password)) + my_token));

实用性:

public string getMD5(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }

    public string getHex(string asciiString)
    {
        string hex = "";
        foreach (char c in asciiString)
        {
            int tmp = c;
            hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
        }
        return hex;
    }

@Gio:你可能已经知道了,但以防万一:C#根本没有加密支持。然而,.NET Framework有,就像Mitch在下面回答的那样。 - John Saunders
1个回答

7

System.Security.Cryptography命名空间中使用.NET的MD5类

上面的链接包含一个简短的代码示例;您可能还想查看Jeff Attwood的CodeProject文章.NET加密简化


1
我真傻,没有仔细检查我复制粘贴的实用函数,结果发现MD5已经将数据转换成十六进制了。 - Gio Borje

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接