asp.net MD5的用法

来源:互联网 发布:包师语 安河桥 知乎 编辑:程序博客网 时间:2024/06/05 02:10

在ASP.NET中提供了加密的解决方法。在名字空间System.Web.Security中包含了类FormsAuthentication,其中有一个方法HashPasswordForStoringInConfigFile。这个方法可以将用户提供的字符变成乱码,然后存储起来,甚至可以 存储在cookies中。
HashPasswordForStoringInConfigFile方法使用起来很简单,它支持"SHA1"和"MD5"加密算法。

两种加密方法:

using System.Web.Security;

 

SHA1.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text,"SHA1");
MD5.Text =FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5") ;

 

如果要用于加密中文字符时,上面那种就有点问题了

比如aspnet和asp做比较:

当要进行MD5加密的字符串不含中文时,那么ASP.NET的加密结果和ASP是一致的:

Response.Write(FormsAuthentication.HashPasswordForStoringInConfigFile("www.mzwu.com", "MD5"));
//结果:D66E1F138689B9B5AA4C520D9EAFFB61

Response.Write(MD5("www.mzwu.com",32))
'结果:d66e1f138689b9b5aa4c520d9eaffb61

当要进行MD5加密的字符串含中文时,两者的加密结果就不一致了:

Response.Write(FormsAuthentication.HashPasswordForStoringInConfigFile("测试数据", "MD5"));
//结果:34D9CBD5164C47058DFA3AF832E2D1DC

Response.Write(MD5("测试数据",32))
'结果:0a40a90190da023ae7aa17771663a41e

 

我们知道,ASP.NET默认使用utf-8编码格式,而ASP使用的是gb2312编码格式,正是由于这编码格式不同,才导致了两者对中文加密结果的不同。下边我们看看怎么让ASP.NET的编码结果和ASP一样,那也就意味着要让ASP.NET采用gb2312编码格式,这点FormsAuthentication.HashPasswordForStoringInConfigFile()方法是办不到的,我们得使用System.Security.Cryptography.MD5CryptoServiceProvider对象的ComputeHash方法来进行加密:

 

using System.Security.Cryptography;

 

MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
Response.Write(BitConverter.ToString(MD5.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes("木子屋"))).Replace("-", ""));
//结果:0A40A90190DA023AE7AA17771663A41E

输出正确

原创粉丝点击