首先,先简单介绍一下MD5
MD5的全称是message-digest algorithm 5(信息-摘要算法,在90年代初由mit laboratory for computer science和rsa data security inc的ronald l. rivest开发出来, 经md2、md3和md4发展而来。
MD5具有很好的安全性(因为它具有不可逆的特征,加过密的密文经过解密后和加密前的东东相同的可能性极小)
引用
using System.Security.Cryptography;
using System.Text;
具体代码如下(写在按钮的Click事件里):
byte[] result = Encoding.Default.GetBytes(this.tbPass.Text.Trim()); //tbPass为输入密码的文本框
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
this.tbMd5pass.Text = BitConverter.ToString(output).Replace("-",""); //tbMd5pass为输出加密文本的文本框
方法二
C# md5加密(上)
string a; //加密前数据
string b; //加密后数据
b=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a,"MD5")
using System;
using System.Security.Cryptography;
方法2
public static string GetMD5(string myString)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
byte[] targetData = md5.ComputeHash(fromData);
string byte2String = null;
for (int i=0; i<targetData.Length; i++)
{
byte2String += targetData[i].ToString("x");
}
return byte2String;
}
using System.Security.Cryptography;
/// <summary>
/// 给一个字符串进行MD5加密
/// </summary>
/// <param >待加密字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5Encrypt(string strText)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
return System.Text.Encoding.Default.GetString(result);
}
C# MD5加密
using System.Security.Cryptography;
private void btnOK_Click(object sender, System.EventArgs e)
{
string strConn = "server=192.168.0.51;database=chengheng;User id=sa; password=123";
if(texName.Text.Trim()=="")
{
this.RegisterStartupScript("sf","<script language=‘javascript‘>alert(‘用户名不能为空‘);document.all(‘texName‘).focus()</script>");
return;
}
else if(texPassword.Text.Trim()=="")
{
this.RegisterStartupScript("sfs","<script language=‘javascript‘>alert(‘密码不能为空‘);document.all(‘texPassword‘).focus()</script>");
return;
}
else
{
//将获取的密码加密与数据库中加了密的密码相比较
byte[] by = md5.ComputeHash(utf.GetBytes(texPassword.Text.Trim()));
string resultPass = System.Text.UTF8Encoding.Unicode.GetString(by);
conn.ConnectionString=strConn;
SqlCommand comm = new SqlCommand();
string name = texName.Text.Trim().ToString();
comm.CommandText="select Ruser_pwd,Ruser_nm from Ruser where Accountno = @name";
comm.Parameters.Add("@name",SqlDbType.NVarChar,40);
comm.Parameters["@name"].Value=name;
try
{
conn.Open();
comm.Connection=conn;
SqlDataReader dr=comm.ExecuteReader();
if(dr.Read())
{
//用户存在,对密码进行检查
if(dr.GetValue(0).Equals(resultPass))
{
string user_name=dr.GetValue(1).ToString();
string user_Accountno=texName.Text.Trim();
Session["logon_name"]=user_name;
Session["logon_Accountno"]=user_Accountno;
//登录成功,进行页面导向