用ASP.NET加密口令(轉)
2024-07-10 12:58:14
供稿:網友
用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
在數據庫應用程序中使用加密方法
每當你向數據庫中增加一個用戶記錄時,都要使用這個函數來加密口令,并將這個口令作為加密過的字符串插入字符串中。當用戶登錄你的站點時,用這個函數對用戶輸入的口令進行加密,然后將它與從數據庫中恢復的那個加密口令進行比較。