Sure, here's a class with necessary methods for encrypting and decrypting password in a C# Windows Form application.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class PasswordEncryptDecryptHelper
{
private static readonly byte[] salt = Encoding.ASCII.GetBytes("Your_Entity_Specific_Salt_Value");
public static string EncryptPassword(string password)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
using (var aes = Aes.Create())
{
var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, salt, 10000);
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(passwordBytes, 0, passwordBytes.Length);
cryptoStream.Close();
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}
public static string DecryptPassword(string encryptedPassword)
{
byte[] encryptedPasswordBytes = Convert.FromBase64String(encryptedPassword);
using (var aes = Aes.Create())
{
var pbkdf2 = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes("Your_Password"), salt, 10000);
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(encryptedPasswordBytes, 0, encryptedPasswordBytes.Length);
cryptoStream.Close();
}
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
}
}
You can use EncryptPassword
method to encrypt the user password before storing it into database and use DecryptPassword
method to decrypt it while retrieving from database for user authentication. Note that you need to set a specific salt value for your entity to enhance the security of your passwords. In the above code, replace Your_Entity_Specific_Salt_Value
with your salt value.