MD5普通加密方法(這種方法一般不做為使用者密碼的加密)
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { //擷取要加密的欄位,並轉化為Byte[]數組 byte[] data = System.Text.Encoding.Unicode.GetBytes(source.Text.ToCharArray()); //建立Data Encryption Service System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); //加密Byte[]數組 byte[] result = md5.ComputeHash(data); //將加密後的數組轉化為欄位 string sResult = System.Text.Encoding.Unicode.GetString(result); //顯示出來 pass_1.Text = sResult.ToString() ; } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>MD5加密 www.itstudy.cn</title> </head> <body> <form id="form1" runat="server"> MD5普通加密:<asp:label id="pass_1" runat="server"></asp:label> <br /> <asp:textbox ID="source" runat="server" Text="test" AutoPostBack="true" /> (斷行符號) </form> </body> </html> |
MD5密碼加密(這是常用的方法)
頁面:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server" TextMode="Password"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="MD5加密" onclick="Button1_Click" /> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> </div> </form> </body> </html> |
後台代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Computer c = new Computer(); } protected void Button1_Click(object sender, EventArgs e) { //作為密碼方式加密 string EnPswdStr = md5(TextBox1.Text,16); //顯示出來 TextBox2.Text = EnPswdStr; } public string md5(string str, int code) //code 16 或 32 { if (code == 16) //16位MD5加密(取32位加密的9~25字元) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16); } if (code == 32) //32位加密 { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower(); } return "00000000000000000000000000000000"; } } |
註:除了採用單一的加密方法,還可以使用多個加密方法,取多個加密後的某幾位組成一個新的加密結果。