用ASP.NET加密口令
每當(dāng)我們要建立數(shù)據(jù)庫驅(qū)動(dòng)的個(gè)人化的web站點(diǎn)時(shí),都必須要保護(hù)用戶的數(shù)據(jù)。盡管黑客可以盜取個(gè)人的口令,然而更嚴(yán)重的問題是有人能夠盜走整個(gè)數(shù)據(jù)庫,然后立刻就是所有的口令。
原理
有一個(gè)好的做法是不將實(shí)際的口令存儲在數(shù)據(jù)庫中,而是存儲它們加密后的版本。當(dāng)我們需要對用戶進(jìn)行鑒定時(shí),只是對用戶的口令再進(jìn)行加密,然后將它與系統(tǒng)中的加密口令進(jìn)行比較即可。
在ASP中,我們不得不借助外部對象來加密字符串。而.NET SDK解決了這個(gè)問題,它在System.Web.Security 名稱空間中的CookieAuthentication類中提供了HashPasswordForStoringInConfigFile方法,這個(gè)方法的目的正如它的名字所提示的,就是要加密存儲在配置文件甚至cookies中的口令。
例子
HashPasswordForStoringInConfigFile方法使用起來非常簡單,它支持用于加密字符串的“SHA1”和“MD5”散列算法。為了看看“HashPasswordForStoringInConfigFile”方法的威力,讓我們創(chuàng)建一個(gè)小小的ASP.NET頁面,并且將字符串加密成SHA1和MD5格式。下面是這樣的一個(gè)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>
點(diǎn)擊這里進(jìn)行演示。 你可以看到,加密口令就是這么簡單。我們還可以將這個(gè)功能包裝在一個(gè)函數(shù)中,隨時(shí)可以再利用它:
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
在數(shù)據(jù)庫應(yīng)用程序中使用加密方法
每當(dāng)你向數(shù)據(jù)庫中增加一個(gè)用戶記錄時(shí),都要使用這個(gè)函數(shù)來加密口令,并將這個(gè)口令作為加密過的字符串插入字符串中。當(dāng)用戶登錄你的站點(diǎn)時(shí),用這個(gè)函數(shù)對用戶輸入的口令進(jìn)行加密,然后將它與從數(shù)據(jù)庫中恢復(fù)的那
|