动网论坛,站长建站首选,国内使用量最多的论坛软件 动网论坛官方技术讨论区 站长工具 申请属于您自己的免费论坛
首页 | 新闻资讯 | 网站运营 | 网络编程 | 数据库 | 服务器 | 网页设计 | 图像媒体 | 网络应用 | 搜索优化 | 资源下载 | 动网主机 | DVBOX
    本站内  互联网 ASP论坛  ASP.Net论坛  PHP论坛
  
   .Net → 阅读文章

 使用ASP.NET加密口令

作者来源: 
阅读 1595 人次 , 2006-3-29 4:33:00 

  当我们在网站上建立数据库时,保护用户的信息安全是非常必要的。多数用户不愿意让别人知道自己的信息,同时网管也不想因为安全问题而丢失网站的信誉。无论对于谁,安全问题都是非常重要的。
  为了解决这个问题,我给大家提供一个简单实用,但是老套的方法,就是口令加密。在此我们使用asp.net技术对口令加密。简单的讲,就是将用户提供的口令加密之后,然后让它和存放于系统中的数据比较,如果相同,则通过验证。
  在asp中,并未提供加密的对象,我们只能使用外部的对象来进行加密。现在好了,在asp.net中提供了加密的解决方法。在名字空间
system.web.security中包含了类formsauthentication,其中有一个方法hashpasswordforstoringinconfigfile。这个方法可以将用户提供
的字符变成乱码,然后存储起来,甚至可以 存储在cookies中。
  hashpasswordforstoringinconfigfile方法使用起来很简单,它支持"sha1"和"md5"加密算法。
  下面的代码简单的演示了关于其用法:
  <%@ page language="c#" %>
  <%@ import namespace="system.web.security" %>
  <html>
<head>
<script language="c#" runat="server">
public void encryptstring(object sender, eventargs e)
{
sha1.text =
formsauthentication.hashpasswordforstoringinconfigfile
(txtpassword.text,"sha1");
md5.text
=formsauthentication.hashpasswordforstoringinconfigfile
(txtpassword.text, "md5") ;
}
</script>
</head>
<body>
<form runat="server" id="form1">
<p>
<b>original clear text password: </b>
<br>
<asp:textbox id="txtpassword" runat="server" />
<asp:button runat="server" text="encrypt string"
onclick="encryptstring" id="button1" />
</p>
<p>
<b>encrypted password in sha1: </b>
<asp:label id="sha1" runat="server" />
</p>
<p>
<b>encrypted password in md5: </b>
<asp:label id="md5" runat="server" />
</p>
</form>
</body>
  </html>



  正如你所看到的这样简单易用。我们可以把这段加密程序封装在一个函数里便于重复的使用。代码如下:
  public string encryptpassword(string
passwordstring,string passwordformat )
{
if (passwordformat="sha1"){

encryptpassword=formsauthortication.hashpasswordforstoringin
configfile(passwordstring ,"sha1");
}
elseif (passwordformat="md5")
{
encryptpassword=formsauthortication.hashpasswordforstoringin
configfile(passwordstring ,"md5");
}
else
{
encryptpassword="";
}

  我们可以在数据库中添加一个字段,使用insert将加密的口令作为一个string存入数据库中。当用户登陆的时候,就可以将用户输入的口令加密结果和数据库中的正确结果比较,通过这种办法来验证口令的正确性了。在此,我就不往下写了,关于数据库的知识还得读者自己去学习。

 本文Tagsmd5  加密  C#  
 收藏本文  打印本文  论坛讨论  关闭窗口
· 上一篇:操作Excel(C#)
· 下一篇:在DataSet中建立外键约束
· 网页的种类
· 一个实现自动求和/合并单元格/排序的DataGrid
· C#中对注册表的操作
· asp.NET中使用include
· 使用SQLDMO从SQL Server中获取信息


关于本站 | 联系我们 | 业务合作 | 客户案例 | 诚聘英才 | 广告合作 | 收藏本站
海口动网先锋网络科技有限公司版权所有
Copyright © 2000 - 2006 Cndw.Com
中华人民共和国电信与信息服务业务经营许可证编号 琼 ICP 020077