Thumb

Part-7: Point of Sale(POS) Convert Password to MD5 Hash string in ASP.NET | Encrypt password in ASP.NET MVC C#

6/7/2020 12:00:00 AM

Download Project

See previous article/video before starting this

Step-1:

  • Create a class name “AppHelper” inside “Helper” folder.
  • Paste below code inside the “AppHelper” class
        public static string GetMd5Hash(string input)
        {
            MD5 md5Hash = MD5.Create();
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

Step-2:

  • Replace your previous “CheckLogin” method inside Home controller by below code
        public JsonResult CheckLogin(string username, string password)
        {
            POS_TutorialEntities db = new POS_TutorialEntities();
            string md5StringPassword = AppHelper.GetMd5Hash(password);
            var dataItem = db.Users.Where(x => x.Username == username && x.Password == md5StringPassword).SingleOrDefault();
            bool isLogged = true;
            if (dataItem != null)
            {
                Session["Username"] = dataItem.Username;
                Session["Role"] = dataItem.Role;
                isLogged = true;
            }
            else
            {
                isLogged = false;
            }
            return Json(isLogged, JsonRequestBehavior.AllowGet);
        }
  • Run the project

About Teacher

Image

Reza Karim

Software Engineer

More about him