当前位置: 移动技术网 > 网络运营>安全>加解密 > 如何使用ASP.NET加密口令

如何使用ASP.NET加密口令

2018年02月27日  | 移动技术网网络运营  | 我要评论
当我们在网站上建立数据库时,保护用户的信息安全是非常必要的。多数用户不愿意让别人知道自己的信息,同时网管也不想因为安全问题而丢失网站的信誉。无论对于谁,安全问题都是非常重... 15-09-16
为了解决这个问题,我给大家提供一个简单实用,但是老套的方法,就是口令加密。在此我们使用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.hashpasswordforstoringinconfigfile(passwordstring ,"sha1");
}
elseif (passwordformat="md5")
{ encryptpassword=formsauthortication.hashpasswordforstoringinconfigfile(passwordstring ,"md5");
}
else
{
encryptpassword="";
}

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

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网