In this article I will explain with an example, how to encrypt and store Username or Password in SQL Server Database Table and then fetch, decrypt and display it in ASP.Net MVC.
The Username or Password will be first encrypted using Symmetric (Same) key AES Algorithm and then will be stored in the database.
The Decryption will be done by fetching the encrypted Username or Password from Database and then decrypting it using the same key that was used for encryption.
 
 
Database
I have created a new database named UsersDB which consist of one table named Users with the following schema.
The Password column has been defined as NVARCHAR type, so that it can easily store encrypted password containing special characters.
ASP.Net MVC: Encrypt and Decrypt Username or Password stored in database
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Security.Cryptography;
 
 
Model
The Model class consists of the following properties needed for populating the records of Users from database.
public class UserModel
{
    public string Username { get; set; }
    public string EncryptedPassword { get; set; }
    public string DecryptedPassword { get; set; }
}
 
 
Controller
The Controller consists of following two Action methods.
The following functions Encrypt and Decrypt will be used to perform encryption and decryption.
Note: For more details on using AES Encryption Decryption in ASP.Net MVC refer my article, ASP.Net MVC: AES Encryption Decryption (Cryptography) Tutorial with example.
 
Action method for handling GET operation
Inside this Action method, the GetUsers method is called.
Inside the GetUsers method, the records from the Users table are fetched using DataReader and generic list of UserModel class objects is populated.
Finally, the generic list of UserModel class objects is returned to the View.
 
Action method for handling POST operation
This Action method handles the call made from the POST function from the View when the Submit Button is clicked.
Inside this Action method, the values of Username and Password are fetched and inserted into the SQL Server database table.
The Username is inserted directly but the Password is first encrypted using the Encrypt function and then it is inserted.
Finally, the GetUsers method is called and returned to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View(GetUsers());
    }
 
    [HttpPost]
    public ActionResult Index(string userName, string password)
    {
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "INSERT INTO Users VALUES (@Username, @Password)";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Username", userName);
                cmd.Parameters.AddWithValue("@Password", Encrypt(password));
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
 
        return View(GetUsers());
    }
 
    private static List<UserModel> GetUsers()
    {
        List<UserModel> users = new List<UserModel>();
        string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT Username, Password FROM Users"))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        users.Add(new UserModel
                        {
                            Username = sdr["Username"].ToString(),
                            EncryptedPassword = sdr["Password"].ToString(),
                            DecryptedPassword = Decrypt(sdr["Password"].ToString())
                        });
                    }
                }
                con.Close();
            }
        }
        return users;
    }
 
    private static string Encrypt(string clearText)
    {
        string encryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
 
    private static string Decrypt(string cipherText)
    {
        string encryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}
 
View
Inside the View, in the very first line the UserModel class is declared as IEnumerable which specifies that it will be available as a Collection.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of two HTML Input TextBox elements and a Submit Button.
When the Submit Button is clicked, the Index Action method for handling POST operation will be called.
 
Displaying the Usernames and the Encrypted and Decrypted Passwords
For displaying the User records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the User records.
@model IEnumerable<Encrypt_Decrypt_Database_MVC.Models.UserModel>
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table border="0" cellpadding="0" cellspacing="0">
            <tr>
                <td>Username:</td>
                <td><input type="text" name="userName" /></td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" name="password" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    }
    <hr/>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>Username</th>
            <th>Encrypted Password</th>
            <th>Decrypted Password</th>
        </tr>
        @foreach (var user in Model)
        {
            <tr>
                <td>@user.Username</td>
                <td>@user.EncryptedPassword</td>
                <td>@user.DecryptedPassword</td>
            </tr>
        }
    </table>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: Encrypt and Decrypt Username or Password stored in database
 
 
Downloads