日期:2012-01-11  浏览次数:20579 次

NET提供了进行数据加密类,下面就用例子进行说明如何使用MD5进行数据加密。

首先,创建一个UserAccount表,字段两个:UserName和Password,类型分别为varchar(25)和binary(16),下面的ASP.NET代码就是创建用户时的具体实现:

<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server" language="VB">
Sub CreateAccount(sender as Object, e as EventArgs)
'1. 创建连接
Const strConnString as String
strConnString= "Data Source=.;Initial Catalog=test;User Id=sa;Password=;"
Dim objConn as New SqlConnection(strConnString)

'2. 创建Command对象
Dim strSQL as String = _
"INSERT INTO UserAccount(Username,Password) " & _
"VALUES(@Username, @Password)"
Dim objCmd as New SqlCommand(strSQL, objConn)

'3. 创建参数
Dim paramUsername as SqlParameter
paramUsername = New SqlParameter("@Username", SqlDbType.VarChar, 25)
paramUsername.Value = txtUsername.Text
objCmd.Parameters.Add(paramUsername)


'加密密码字段

Dim md5Hasher as New MD5CryptoServiceProvider()

Dim hashedBytes as Byte()
Dim encoder as New UTF8Encoding()

hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(txtPwd.Text))

Dim paramPwd as SqlParameter
paramPwd = New SqlParameter("@Password", SqlDbType.Binary, 16)
paramPwd.Value = hashedBytes
objCmd.Parameters.Add(paramPwd)


'插入数据库
objConn.Open()
objCmd.ExecuteNonQuery()
objConn.Close()

'Redirect 其它页面
End Sub
</script>

<form runat="server">
<h1>创建帐号:</h1>
用户名: <asp:TextBox runat="server" id="txtUsername"/>
<br/>
密码: <asp:TextBox runat="server" id="txtPwd" TextMode="Password"/>
<p><asp:Button runat="server" Text="创建用户" OnClick="CreateAccount"/></p>
</form>

下面是对用户进行验证的ASP.NET代码:


<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server" language="VB">
Sub Login(sender as Object, e as EventArgs)
'1. 创建连接
Const strConnString as String
strConnString= "Data Source=.;Initial Catalog=test;User Id=sa;Password=;"
Dim objConn as New SqlConnection(strConnString)

'2. 创建Command对象
Dim strSQL as String = "SELECT COUNT(*) FROM UserAccount " & _
"WHERE Username=@Username AND Password=@Password"
Dim objCmd as New SqlCommand(strSQL, objConn)

'3. 创建参数
Dim paramUsername as SqlParameter
paramUsername = New SqlParameter("@Username", SqlDbType.VarChar, 25)
paramUsername.Value = txtUsername.Text
objCmd.Parameters.Add(paramUsername)


'加密密码
Dim md5Hasher as New MD5CryptoServiceProvider()

Dim hashedDataBytes as Byte()
Dim encoder as New UTF8Encoding()

hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(txtPwd.Text))

Dim paramPwd as SqlParameter
paramPwd = New SqlParameter("@Password", SqlDbType.Binary, 16)
paramPwd.Value = hashed