Storing plain-text password into database is completely insecure and not recommended. Several methods to store encrypted password such as using LDAP server or hashing the password before saving to database.
Below is an example how to hash the password using MD5 before writing to database and authenticate user.
//In order to use MD5 class, we need to import System.Security.Cryptography; using System.Security.Cryptography; //MD5 Hashstring static method public static string MD5HashString(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(); } //Create user login method public bool createUserAccount(string strUsername, string strPassword) { //validation //check if username is valid if(!UserEntity.isValidUsername(strUsername)){ //username invalid return false; } //check if password is valid if(!UserEntity.isValidPassword(strPassword)){ //password entered fail password policy validation return false; } //all validation passed //md5 hash user password string hashUserPassword = common.CommonFunction.MD5HashString(strPassword); //initialize data access layer object UserDA objUserDa = new UserDA(); //write to database bool insertResult = objUserDa.createNewUser(strUsername, hashUserPassword); return insertResult; } //Authenticate user public bool userLogin(string strUsername, string strPassword) { //check whether user login valid UserDA objUserDa = new UserDA(); //retrieve user id by username int userId = objUserDa.getUseridByUsername(strUsername); if(userId == -1) { //user records not found return false; } //convert user password to md5 string md5password = common.CommonFunction.MD5HashString(strPassword); //retrieve user md5 password from database string strDBUserMd5Password = objUserDa.getUserPassword(userId); //compare password StringComparer comparer = StringComparer.OrdinalIgnoreCase; //ignore case if (0 == comparer.Compare(strDBUserMd5Password, md5password)) { //password matched //user's credential is valid } else { //password don't match return false; } //retrieve user type userType = objUserDa.getUserType(userId); //start logged in session startLoginSession(userId, strUsername); return true; }
That’s all. Hope it helps.