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 get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article