服务器 > 网络安全 > 加密解密

如何使用ASP.NET加密口令

56人参与 2015-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存入数据库中。当用户登陆的时候,就可以将用户输入的口令加密结果和数据库中的正确结果比较,通过这种办法来验证口令的正确性了。在此,我就不往下写了,关于数据库的知识还得读者自己去学。
(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

电子邮件加密3种方式

09-23

加密解密那些事之SSL(https)中的对称加密与非对称加密

07-17

系统安全之隐藏文件方法 做到保护个人隐私安全

10-08

用邮件pops加密程序不想让别人看到

01-21

如何在Win7系统下创建带密码的隐藏文件夹

10-08

PDF文件加密的三种方法介绍

09-17

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论