用ASP.NET加密口令(轉)
最後更新:2017-02-28
來源:互聯網
上載者:User
asp.net|加密 用ASP.NET加密口令
每當我們要建立資料庫驅動的個人化的web網站時,都必須要保護使用者的資料。儘管駭客可以盜取個人的口令,然而更嚴重的問題是有人能夠盜走整個資料庫,然後立刻就是所有的口令。
原理
有一個好的做法是不將實際的口令儲存在資料庫中,而是儲存它們加密後的版本。當我們需要對使用者進行評鑑時,只是對使用者的口令再進行加密,然後將它與系統中的加密口令進行比較即可。
在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
在資料庫應用程式中使用加密方法
每當你向資料庫中增加一個使用者記錄時,都要使用這個函數來加密口令,並將這個口令作為加密過的字串插入字串中。當使用者登入你的網站時,用這個函數對使用者輸入的口令進行加密,然後將它與從資料庫中恢複的那個加密口令進行比較。