用ASP.NET加密口令
作者:未知 来源:青苹果工作室 添加时间:2006-5-21 10:47:11| 原理 |
有一个好的做法是不将实际的口令存储在数据库中,而是存储它们加密后的版本。当我们需要对用户进行鉴定时,只是对用户的口令再进行加密,然后将它与系统中的加密口令进行比较即可。
在ASP中,我们不得不借助外部对象来加密字符串。而.NET SDK解决了这个问题,它在System.Web.Security 名称空间中的CookieAuthentication类中提供了HashPasswordForStoringInConfigFile方法,这个方法的目的正如它的名字所提示的,就是要加密存储在配置文件甚至cookies中的口令。
| 例子 |
HashPasswordForStoringInConfigFile方法使用起来非常简单,它支持用于加密字符串的“SHA1”和“MD5”散列算法。为了看看“HashPasswordForStoringInConfigFile”方法的威力,让我们创建一个小小的ASP.NET页面,并且将字符串加密成SHA1和MD5格式。下面是这样的一个ASP.NET页面源代码:
| <%@ Import Namespace="System.Web.Security" %> <html> <head> <script language="VB" runat=server> ' This function encrypts the input string using the SHA1 and MD5 ' encryption algorithms Sub encryptString(Src As Object, E As EventArgs) SHA1.Text = CookieAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1") MD5.Text = CookieAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5") End Sub </script> </head> <body> <form runat=server> <p><b>Original Clear Text Password: </b><br> <asp:Textbox id="txtPassword" runat=server /> <asp:Button runat="server" text="Encrypt String" onClick="encryptString" /></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> |
点击这里进行演示。
你可以看到,加密口令就是这么简单。我们还可以将这个功能包装在一个函数中,随时可以再利用它:
| Function EncryptPassword (PasswordString as String, PasswordFormat as String) as String If PasswordFormat = "SHA1" then EncryptPassword = CookieAuthentication.HashPasswordForStoringInConfigFile(PasswordString, "SHA1") Elseif PasswordFormat = "MD5" then EncryptPassword= CookieAuthentication.HashPasswordForStoringInConfigFile(PasswordString, "MD5") Else EncryptPassword = "" End if End Function |
| 在数据库应用程序中使用加密方法 |
每当你向数据库中增加一个用户记录时,都要使用这个函数来加密口令,并将这个口令作为加密过的字符串插入字符串中。当用户登录你的站点时,用这个函数对用户输入的口令进行加密,然后将它与从数据库中恢复的那个加密口令进行比较。
站内搜索