c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
entity framework

How to create password encryption and decryption in c# asp.net (entity framework)?

| | ASP-NET , CSharp , MVC , SQL

In this article, I will show you how to create password encryption and decryption in c# asp.net. I am going to encrypt password before saving using the entity framework sql server.

When the user tries to sign in, decrypts the password field before reading from the database.  For that, create a [Not Mapped] property in the UserLogin object as below.

 

Save user object using entity framework

userlogin.Password= Encrypt_Password(userlogin.Password);
db.Entry(userlogin).State= EntityState.Modified;
db.SaveChanges();

Encrption function:

private string Encrypt_Password(string password)
        {
            string pswstr = string.Empty;
            byte[] psw_encode = new byte[password.Length];
            psw_encode = System.Text.Encoding.UTF8.GetBytes(password);
            pswstr = Convert.ToBase64String(psw_encode);
            return pswstr;
        }  

UserLogin class:

using System.ComponentModel.DataAnnotations.Schema;

   
public partial class UserLogin
    {
       public int UserId { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }

        [
NotMapped]
        public string DecryptedPassword
        {
            get { return Decrypt_Password(Password); }
            set { Password = Decrypt_Password(value); }
        }

       private string Decrypt_Password(string encryptpassword)
        {
            string pswstr = string.Empty;
            System.Text.UTF8Encoding encode_psw = new System.Text.UTF8Encoding();
            System.Text.Decoder Decode = encode_psw.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(encryptpassword);
            int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            pswstr = new String(decoded_char);
            return pswstr;
        }
    }

Postback Login page:  

The user password field should be decrypted after the objects from the database,

var login = db.UserLogins.Where(x => x.Name == userlogin.Name && x.Password == userlogin.Password);
if (login.Count() > 0)
 {
  //you logic

 }