|
<p >每当我们要建立数据库驱动的个人化的web站点时,都必须要保护用户的数据。尽管黑客可以盗取个人的口令,然而更严重的问题是有人能够盗走整个数据库,然后立刻就是所有的口令。<p ><ccid_nobr><table width="100%" bgcolor="#f7f3f7" ><tr><td><font color="#000084">原理</font></td></tr></table></ccid_nobr><p >有一个好的做法是不将实际的口令存储在数据库中,而是存储它们加密后的版本。当我们需要对用户进行鉴定时,只是对用户的口令再进行加密,然后将它与系统中的加密口令进行比较即可。<p >在ASP中,我们不得不借助外部对象来加密字符串。而.NET SDK解决了这个问题,它在System.Web.Security 名称空间中的CookieAuthentication类中提供了HashPasswordForStoringInConfigFile方法,这个方法的目的正如它的名字所提示的,就是要加密存储在配置文件甚至cookies中的口令。<p ><ccid_nobr><table width="100%" bgcolor="#f7f3f7" ><tr><td><font color="#000084">例子</font></td></tr></table></ccid_nobr><p >HashPasswordForStoringInConfigFile方法使用起来非常简单,它支持用于加密字符串的“SHA1”和“MD5”散列算法。为了看看“HashPasswordForStoringInConfigFile”方法的威力,让我们创建一个小小的ASP.NET页面,并且将字符串加密成SHA1和MD5格式。下面是这样的一个ASP.NET页面源代码:<p ><ccid_nobr><table width="580" border="1" cellspacing="0" cellpadding="0" bordercolorlight="black" bordercolordark="#ffffff"><tr><td bgcolor="e6e6e6" class="code"><%@ Import Namespace="System.Web.Security" %><br/><html><br/><head><br/><script language="VB" runat=server><br/>' This function encrypts the input string using the SHA1 and MD5<br/>' encryption algorithms<br/>Sub encryptString(Src As Object, E As EventArgs)<br/>SHA1.Text = CookieAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1")<br/>MD5.Text = CookieAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5")<br/>End Sub<br/></script><br/></head><br/><body><br/><form runat=server><br/><p><b>Original Clear Text Password: </b><br><br/><asp:Textbox id="txtPassword" runat=server /><br/><asp:Button runat="server" text="Encrypt String" onClick="encryptString" /></p><br/><p><b>Encrypted Password In SHA1: </b><br/><asp:label id="SHA1" runat=server /></p><br/><p><b>Encrypted Password In MD5: </b><br/><asp:label id="MD5" runat=server /></p><br/></form><br/></body><br/></html></td></tr></table></ccid_nobr><p ><ccid_nobr>点击这里</ccid_nobr>进行演示。<p >你可以看到,加密口令就是这么简单。我们还可以将这个功能包装在一个函数中,随时可以再利用它:<p ><ccid_nobr><table width="580" border="1" cellspacing="0" cellpadding="0" bordercolorlight="black" bordercolordark="#ffffff"><tr><td bgcolor="e6e6e6" class="code">Function EncryptPassword (PasswordString as String, PasswordFormat as String) as String<br/>If PasswordFormat = "SHA1" then<br/>EncryptPassword = CookieAuthentication.HashPasswordForStoringInConfigFile(PasswordString, "SHA1")<br/>Elseif PasswordFormat = "MD5" then<br/>EncryptPassword= CookieAuthentication.HashPasswordForStoringInConfigFile(PasswordString, "MD5")<br/>Else<br/>EncryptPassword = ""<br/>End if<br/>End Function</td></tr></table></ccid_nobr><p ><ccid_nobr><table width="100%" bgcolor="#f7f3f7" ><tr><td><font color="#000084">在数据库应用程序中使用加密方法</font></td></tr></table></ccid_nobr><p >每当你向数据库中增加一个用户记录时,都要使用这个函数来加密口令,并将这个口令作为加密过的字符串插入字符串中。当用户登录你的站点时,用这个函数对用户输入的口令进行加密,然后将它与从数据库中恢复的那个加密口令进行比较。<p >(责任编辑 <ccid_nobr>尤北</ccid_nobr>) <p align="center"></p></p> |
|