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
- Your system's memory configuration has changed since it entered hibernation.
- Save image to client browser using jQuery?
- Get filename of image jQuery?
- How to get the image src using JavaScript?
- System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Net.Http.Formatting' with identity 'System.Net.Http.Formatting, Version=4.0.0.0
- Cordova Android build error "Cannot read property 'length' of undefined". An error occurred while running subprocess cordova.
- ERROR in The Angular Compiler requires TypeScript >=3.9.2 and <4.0.0 but 3.8.3 was found instead
- Code ENOLOCAL Could not install from "android" as it does not contain a package.json file.
Related Article