using System.Security.Cryptography;
using System.Text; StringBuilder sb = new StringBuilder();//构建一个字符串,来接受进行算法后的字符串
using (MD5 md=MD5.Create())//通过静态方法Creat()创建一个MD5对象
{
//ComputeHash()方法接受的参数为byte[]数组或者流,所以要通过编码将"aa"编码为byte数组,然后再传参
byte[] byteArr = md.ComputeHash(Encoding.UTF8.GetBytes("aa")); for (int i = ; i < byteArr.Length; i++)
{
sb.Append(byteArr[i].ToString("x2"));
}
}
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 = ; 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) > )
{
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 = ; i < endBytes.Length; i++)
{
sb.Append(endBytes[i].ToString("x2"));
}
mdf.Clear();
return sb.ToString();
}