新建一个类Md5Helper
public class Md5Helper
{
#region "MD5加密"
/// <summary>
/// MD5加密
/// </summary>
/// <param name="str">加密字符</param>
/// <param name="code">加密位数16/32</param>
/// <returns></returns>
public static string Encrypt(string str, int code)
{
string strEncrypt = string.Empty;
if (code == 16)
{
strEncrypt = Hash(str).Substring(8, 16);
}
if (code == 32)
{
strEncrypt = Hash(str);
}
return strEncrypt;
}
/// <summary>
/// 32位MD5加密(小写)
/// </summary>
/// <param name="input">输入字段</param>
/// <returns></returns>
public static string Hash(string input)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
#endregion
}
在controller里调用Md5Helper
[HttpPost]
public JsonResult Login(Vendors tempUser)
{
string a = Request.Form["VendorPwdInput"].ToString();
string strDefaultPwd = "123456";
VendorBLL bll = new VendorBLL();
Vendors user = bll.GetVendor(tempUser.VendorId);
var obj = new { status = "" };
if (user != null)
{
string strSecretkey = DESEncrypt.Encrypt(user.VendorId.ToLower(), user.Id.ToLower()).ToLower();
tempUser.VendorPwd = Md5Helper.Encrypt(DESEncrypt.Encrypt(tempUser.VendorPwdInput.ToLower(), strSecretkey).ToLower(), 32).ToLower();
// 密码错误时
if (tempUser.VendorPwd != user.VendorPwd)
{
obj = new { status = "error" };
return Json(obj);
}
// 密码为默认时
strDefaultPwd = Md5Helper.Encrypt(DESEncrypt.Encrypt(strDefaultPwd, strSecretkey).ToLower(), 32).ToLower();
if (user.VendorPwd == strDefaultPwd)
{
//如果密码为123456,提醒修改密码
}
System.Web.Security.FormsAuthentication.SetAuthCookie(user.VendorId, true);
WebHelper.WriteCookie("Current_VendorId", user.VendorId);
WebHelper.WriteCookie("Current_VendorName", user.VendorName);
// 系统全局变量
HttpContext.Cache["current_user"] = user;
ViewData["current_user"] = user;
Session["current_user"] = user;
obj = new { status = "success" };
return Json(obj);
}
else
{
//用户不存在
obj = new { status = "notfind" };
return Json(obj);
}
}