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 enable Search Feature in Django admin?
- How to check PAN-Aadhaar is Linked or NOT?
- How to customize pagination for django admin?
- How to fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
Related Article