在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="";
}
新聞熱點
疑難解答
圖片精選