How to create encrypted login password using C# MVC
Hi All, in this tutorial we will learn how to create encrypted password login page in MVC C#.
Steps involved in this tutorial:
1) Create table tblLogin
2) Generate Entity Data Model
3) Create Helper class to encrypt and decrypt the password
4) Setup create user functionality
5) Setup login user functionality
First we will create database table with name as tblLogin:
Once our table is ready, we will generate the entity class for this table and we will save entity database model with name as - EntityDBModel.
If you dont know how to generate entity data model please checkout below tutorial:
How to add entity framework in visual studio
This is how our entity class will look like:
Now we will create Helper folder and inside that we will create helper class which will provide us the functionality to encrypt & decrypt password
Now we will create login Controller- LoginController
In login controller we will create Get Login Method and Post Login method
Now we will create view for this login account creation:
Right click on CreateLogin method name and click on add view, then select the model name tblLogin and click on Add view.
Below view will be generated:
Now we are able to create the encrypted login passwords accounts in the system via http://localhost/Login/CreateLogin.
Now we will go ahead and try login using this, so we will develop functionality in order to access this system using http://localhost/Account/Login
First we will create Account Controller. In account controller we will create below method:
In case user is not logged in and accessing any page without login, then our system will ask him to login first and then will directly take him to the page which he has requested, this we will handle through returnUrl.
Now we will create view page which will allow us to login to our system. Right click on method Login from Account Controller and click on Add view. View will be generated, and we will pass the login credentials to Login method and will perform authentication.
We will create user now using Login/createLogin:
In the database, user has been created with encrypted password:
Now we will try to login using Account/Login
The user is successfully logged into system.
Done.
You are now able to create login via http://localhost/Login/CreateLogin
You will be able to login to the system using http://localhost/Account/Login
Thanks for reading this blog. I hope it helps.
Steps involved in this tutorial:
1) Create table tblLogin
2) Generate Entity Data Model
3) Create Helper class to encrypt and decrypt the password
4) Setup create user functionality
5) Setup login user functionality
First we will create database table with name as tblLogin:
CREATE TABLE [dbo].[tblLogin]( [Id] [int] IDENTITY(1,1) NOT NULL, [username] [varchar](10) NOT NULL UNIQUE, [password] [varchar](50) NOT NULL, [IsActive] [bit] NULL, [sid] [varchar](16) NOT NULL, [count] [int] NULL, PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
Once our table is ready, we will generate the entity class for this table and we will save entity database model with name as - EntityDBModel.
If you dont know how to generate entity data model please checkout below tutorial:
How to add entity framework in visual studio
This is how our entity class will look like:
using System; using System.Collections.Generic; public partial class tblLogin { public int Id { get; set; } public string username { get; set; } public string password { get; set; } public Nullable<bool> IsActive { get; set; } public string sid { get; set; } public Nullable<int> count { get; set; } }
Now we will create Helper folder and inside that we will create helper class which will provide us the functionality to encrypt & decrypt password
namespace ProjectName.Helper { public static class Helper { public static string GeneratePassword(int length) //length of salt { const string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"; var randNum = new Random(); var chars = new char[length]; var allowedCharCount = allowedChars.Length; for (var i = 0; i <= length - 1; i++) { chars[i] = allowedChars[Convert.ToInt32((allowedChars.Length) * randNum.NextDouble())]; } return new string(chars); } public static string EncodePassword(string pass, string salt) //encrypt password { byte[] bytes = Encoding.Unicode.GetBytes(pass); byte[] src = Encoding.Unicode.GetBytes(salt); byte[] dst = new byte[src.Length + bytes.Length]; System.Buffer.BlockCopy(src, 0, dst, 0, src.Length); System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length); HashAlgorithm algorithm = HashAlgorithm.Create("SHA1"); byte[] inArray = algorithm.ComputeHash(dst); return EncodePasswordMd5(Convert.ToBase64String(inArray)); } public static string EncodePasswordMd5(string pass) //Encrypt using MD5 { Byte[] originalBytes; Byte[] encodedBytes; MD5 md5; md5 = new MD5CryptoServiceProvider(); originalBytes = ASCIIEncoding.Default.GetBytes(pass); encodedBytes = md5.ComputeHash(originalBytes); return BitConverter.ToString(encodedBytes); } public static string base64Encode(string sData) // Encode { try { byte[] encData_byte = new byte[sData.Length]; encData_byte = System.Text.Encoding.UTF8.GetBytes(sData); string encodedData = Convert.ToBase64String(encData_byte); return encodedData; } catch (Exception ex) { throw new Exception("Error in base64Encode" + ex.Message); } } public static string base64Decode(string sData) //Decode { try { var encoder = new System.Text.UTF8Encoding(); System.Text.Decoder utf8Decode = encoder.GetDecoder(); byte[] todecodeByte = Convert.FromBase64String(sData); int charCount = utf8Decode.GetCharCount(todecodeByte, 0, todecodeByte.Length); char[] decodedChar = new char[charCount]; utf8Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decodedChar, 0); string result = new String(decodedChar); return result; } catch (Exception ex) { throw new Exception("Error in base64Decode" + ex.Message); } } } }
Now we will create login Controller- LoginController
In login controller we will create Get Login Method and Post Login method
public class LoginController : Controller { private EntityDBModel db = new EntityDBModel(); // GET: Login/Create public ActionResult CreateLogin() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult CreateLogin([Bind(Include = "Id,username,password,IsActive")] tblLogin tblLogin) { if (ModelState.IsValid) { try { var keyNew = Helper.Helper.GeneratePassword(10); var password = Helper.Helper.EncodePassword(tblLogin.password, keyNew); tblLogin.password = password; tblLogin.sid = keyNew; db.tblLogin.Add(tblLogin); db.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } return RedirectToAction("Index"); } return View(tblLogin); } }
Now we will create view for this login account creation:
Right click on CreateLogin method name and click on add view, then select the model name tblLogin and click on Add view.
Below view will be generated:
@model ProjectName.Models.tblLogin @{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>tblLogin</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.username, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <div class="checkbox"> @Html.EditorFor(model => model.IsActive) @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" }) </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div>
Now we are able to create the encrypted login passwords accounts in the system via http://localhost/Login/CreateLogin.
Now we will go ahead and try login using this, so we will develop functionality in order to access this system using http://localhost/Account/Login
First we will create Account Controller. In account controller we will create below method:
In case user is not logged in and accessing any page without login, then our system will ask him to login first and then will directly take him to the page which he has requested, this we will handle through returnUrl.
//GET public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } [HttpPost] public ActionResult Login(Models.Membership MembershipModel, string returnUrl) { using (var context = new EntityDBModel()) { var getUser = (from s in context.tblLogin where s.username == MembershipModel.username select s).FirstOrDefault(); var hashCode = getUser.sid; //Password Hasing Process Call Helper Class Method var encodingPasswordString = Helper.Helper.EncodePassword(MembershipModel.password, hashCode); //Check Login Detail User Name Or Password bool isValidUser = context.tblLogin.Any(x=> x.username == MembershipModel.username && x.password == encodingPasswordString); if (isValidUser) { FormsAuthentication.SetAuthCookie(MembershipModel.username, true); return Redirect(returnUrl); } else { ModelState.AddModelError("","Invalid Username and password"); } } return View(); }
Now we will create view page which will allow us to login to our system. Right click on method Login from Account Controller and click on Add view. View will be generated, and we will pass the login credentials to Login method and will perform authentication.
@model ProjectName.Models.Membership @{ ViewBag.Title = "Login"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2 class="modal-header">Login</h2> @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) { @Html.AntiForgeryToken() <div class="form-horizontal"> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.username, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.username, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.username, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.password, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" , Type="password"} }) @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Login" class="btn btn-info" /> </div> </div> </div> }
We will create user now using Login/createLogin:
In the database, user has been created with encrypted password:
Now we will try to login using Account/Login
The user is successfully logged into system.
Done.
You are now able to create login via http://localhost/Login/CreateLogin
You will be able to login to the system using http://localhost/Account/Login
Thanks for reading this blog. I hope it helps.
Comments
Post a Comment