MD5算法的使用
1 using System.Security.Cryptography; 2 using System.Text; 3 4 5 StringBuilder sb = new StringBuilder();//构建一个字符串,来接受进行算法后的字符串 6 using (MD5 md=MD5.Create())//通过静态方法Creat()创建一个MD5对象 7 {
//ComputeHash()方法接受的参数为byte[]数组或者流,所以要通过编码将"aa"编码为byte数组,然后再传参 8 byte[] byteArr = md.ComputeHash(Encoding.UTF8.GetBytes("aa")); 9 10 for (int i = 0; i < byteArr.Length; i++) 11 { 12 sb.Append(byteArr[i].ToString("x2")); 13 } 14 } 15 Console.WriteLine(sb.ToString());
=====================================
对文件的MD5计算:
class Program { static void Main(string[] args) { Console.WriteLine("Please input the file's path..."); string path = Console.ReadLine(); FileStream aFiles = new FileStream(path, FileMode.Open, FileAccess.Read) ; Program a = new Program(); a.comput(aFiles); Console.ReadLine(); } public void comput(FileStream mdByteArr) { StringBuilder sb = new StringBuilder(); using (MD5 md = MD5.Create()) { byte[] aFile = md.ComputeHash(mdByteArr);//直接传入一个流的重载 for (int i = 0; i < aFile.Length; i++) { sb.Append(aFile[i].ToString("x2")); } } Console.WriteLine(" md5 value is: {0}", sb.ToString()); } }
用MD5来存储用户密码,实现登陆功能:
private void btnLogin_Click(object sender, EventArgs e) { string name = txtName.Text.Trim(); string pwd = txtPwd.Text.Trim(); string sqlstr = "select count(*) from T_Seats where CC_LoginId=@id and CC_LoginPassword=@pwd"; SqlParameter[] spt = new SqlParameter[] { new SqlParameter("@id",name), new SqlParameter("@pwd",GetMd5Value(pwd))//拿到用户输入的密码的MD5值去跟数据库中的进行比较 }; if ((int)SqlHelper.ExecuteScalar(sqlstr, spt) > 0) { MessageBox.Show("access"); txtRePwd.Visible = true; btnChangePwd.Visible = true; } else { MessageBox.Show("no"); } } private string GetMd5Value(string original) { StringBuilder sb = new StringBuilder(); byte[] bytes = Encoding.Default.GetBytes(original); MD5 mdf = MD5.Create(); byte[] endBytes = mdf.ComputeHash(bytes); for (int i = 0; i < endBytes.Length; i++) { sb.Append(endBytes[i].ToString("x2")); } mdf.Clear(); return sb.ToString(); }

浙公网安备 33010602011771号