在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=””;
}
