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 Core Razor Pages.
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 Core Razor Pages: 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.Security.Cryptography;
using Microsoft.Extensions.Configuration;
 
 
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; }
}
 
 
Razor PageModel (Code-Behind)
The PageModel consists of following two Handler 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 Core Razor Pages, please refer my article ASP.Net Core Razor Pages: AES Encryption Decryption (Cryptography) Tutorial with example.
 
Handler method for handling GET operation
Inside this Handler method, the GetUsers method is called and the public property Users is set.
Inside the GetUsers method, the records from the Users table are fetched using DataReader and generic list of UserModel class objects is populated.
Note: For details about reading Connection String from AppSettings.json, please refer my article .Net Core: Read Connection String from AppSettings.json file.
 
Finally, the generic list of UserModel public property is returned to the Razor Page.
 
Handler method for handling POST operation for uploading Files
This Handler method gets called when the Submit Button is clicked.
Inside this Handler 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 public property Users is set and returned to the Razor Page.
public class IndexModel : PageModel
{
    public List<UserModel> Users { get; set; }
 
    private IConfiguration Configuration;
 
    public IndexModel(IConfiguration _configuration)
    {
        Configuration = _configuration;
    }
 
    public void OnGet()
    {
        this.Users = GetUsers();
    }
 
    public void OnPostSubmit(string userName, string password)
    {
        string constr = this.Configuration.GetConnectionString("MyConn");
        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();
            }
        }
 
        this.Users = GetUsers();
    }
 
    private List<UserModel> GetUsers()
    {
        List<UserModel> users = new List<UserModel>();
        string constr = this.Configuration.GetConnectionString("MyConn");
        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 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 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;
    }
}
 
 
Razor Page (HTML)
Form
Razor HTML Page consists of an HTML Form which has been created using the following attribute.
method – 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.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
 
When the Submit Button is clicked, the Submit Handler 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.
@page
@model Encrypt_Decrypt_Database_Razor_Core.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="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" asp-page-handler="Submit" /></td>
            </tr>
        </table>
    </form>
    <hr/>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <th>Username</th>
            <th>Encrypted Password</th>
            <th>Decrypted Password</th>
        </tr>
        @foreach (var user in Model.Users)
        {
            <tr>
                <td>@user.Username</td>
                <td>@user.EncryptedPassword</td>
                <td>@user.DecryptedPassword</td>
            </tr>
        }
    </table>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Encrypt and Decrypt Username or Password stored in database
 
 
Downloads