本来我也以为System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile中的MD5和常用的一样
可今天一试,结果有很大不同,
比如test,HashPasswordForStoringInConfigFile编码成
C8059E2EC7419F590E79D7F1B774BFE6
而应该是098f6bcd4621d373cade4e832627b4f6
而且不同的机器不同的结果,有些结果正确
一看MSDN的解释,原来是
Given a password and a string identifying the hash type, this routine produces a hash password suitable for storing in a configuration file.
为了和以前的代码兼容和平台兼容,只好自己重新写了MD5的算法,利用System.Security.Cryptography.MD5CryptoServiceProvider
代码如下,大家执行一下就知道了,我就不多说了。
- <%@ Page Language="C#" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <script runat="server">
- string MD5Crypto(string str)
- {
- byte[] b = System.Text.Encoding.Default.GetBytes(str);
- b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
- string ret = "";
- for (int i = 0; i < b.Length; i++)
- ret += b[i].ToString("x").PadLeft(2, '0');
- return ret;
- }
- public void encryptString(Object sender, EventArgs e)
- {
- myMD5.Text = MD5Crypto(txtClear.Text);
- MD5.Text = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtClear.Text, "MD5");
- }
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml" >
- <head runat="server">
- <title>无标题页</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- 明文:<asp:TextBox ID="txtClear" runat="server" />
- <asp:Button runat="server" Text="Md5摘要" OnClick="encryptString" ID="Button1" />
- <br />
- 通常用的 MD5:
- <br />
- <asp:Label ID="myMD5" runat="server" />
- <br />
- <br />
- HashPasswordForStoringInConfigFile中的 MD5:
- <br />
- <asp:Label ID="MD5" runat="server" />
- </div>
- </form>
- </body>
- </html>