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
}
Post your comments / questions
Recent Article
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
- FieldError: Cannot resolve keyword 'id' into field in Django project
- How to hide the ID field from the Django admin?
- It is impossible to add a non nullable field without specifying a default. Django error
Related Article