用户信息的保密性在系统中是不可避免的,比如用户的密码等.这里我们通过代码简单介绍使用MD5加密的方法
代码
/// <summary>
/// MD5加密
/// </summary>
public class MD5
{
private string txt;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="txt">原始字符串</param>
public MD5(string txt)
{
this.txt = txt;
}
public MD5()
{
}
/// <summary>
/// MD5加密
/// </summary>
/// <returns>已加密字符串</returns>
public string EncryptToMd5()
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txt, "MD5");
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="txt">原始字符串</param>
/// <returns>加密字符串</returns>
public string EncryptToMd5(string txt)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txt, "MD5");
}
/// <summary>
/// 设置、获取加密字符串
/// </summary>
public string EncryptText
{
set
{
this.txt = value;
}
get
{
return this.txt;
}
}
/// <summary>
/// 获取加密后的MD5字符串
/// </summary>
public string MD5Code
{
get
{
return EncryptToMd5();
}
}
}
/// MD5加密
/// </summary>
public class MD5
{
private string txt;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="txt">原始字符串</param>
public MD5(string txt)
{
this.txt = txt;
}
public MD5()
{
}
/// <summary>
/// MD5加密
/// </summary>
/// <returns>已加密字符串</returns>
public string EncryptToMd5()
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txt, "MD5");
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="txt">原始字符串</param>
/// <returns>加密字符串</returns>
public string EncryptToMd5(string txt)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txt, "MD5");
}
/// <summary>
/// 设置、获取加密字符串
/// </summary>
public string EncryptText
{
set
{
this.txt = value;
}
get
{
return this.txt;
}
}
/// <summary>
/// 获取加密后的MD5字符串
/// </summary>
public string MD5Code
{
get
{
return EncryptToMd5();
}
}
}
上面构建了一个简单的MD5对象,下面我们可以通过用户输入的密码将其转化为MD5形式来验证是否正确.
//输入密码MD5转换
MD5 md5 = new MD5(userPassword);
string loginPassword = md5.EncryptToMd5();
//密码不一致的时候,错误处理
if (password != loginPassword)
{
return;
}
MD5 md5 = new MD5(userPassword);
string loginPassword = md5.EncryptToMd5();
//密码不一致的时候,错误处理
if (password != loginPassword)
{
return;
}