C# Password Encryption and Decryption Using Secret Key Explained

How to securely encrypt and decrypt password in c#.net using secrete key. This step-by-step tutorial will have code example, best practices.
In today's article I will show you how you can encrypt and decrypt password in c#.net and VB.NET using serrate key. Here I am using CryptoStream to encrypt the password. This tutorial will demonstrate a perfect example of C# AES Encrypt Decrypt example for password, AES key derivation with SHA256 in C#, Example: encrypting user input in WinForms. Here in this article, we will use windows application for showing the example. Here I have user .net core 10. First, we will design the form as shown below to demonstrate the example. 

Encrypt Decrypt Password Form

C#.Net

using System.Security.Cryptography;
using System.Text;

namespace WinFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            string encryptedText = EncryptPassword(txtInput.Text, "1234567");
            txtOutput.Text = encryptedText;
        }
       
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            string decryptedText = DecryptPassword(txtInput.Text, "1234567");
            txtOutput.Text = decryptedText;
        }
        private string EncryptPassword(string plaintext, string key)
        {
            using var aes = Aes.Create();
            using var sha = SHA256.Create();
            aes.Key = sha.ComputeHash(Encoding.UTF8.GetBytes(key)); // 32 bytes
            aes.GenerateIV();

            using var ms = new MemoryStream();
            ms.Write(aes.IV, 0, aes.IV.Length);
            using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                byte[] data = Encoding.UTF8.GetBytes(plaintext);
                cs.Write(data, 0, data.Length);
                cs.FlushFinalBlock();
            }
            return Convert.ToBase64String(ms.ToArray());
        }
        private string DecryptPassword(string encryptedText, string key)
        {
            byte[] cipherBytes = Convert.FromBase64String(encryptedText);
            using var aes = Aes.Create();
            using var sha = SHA256.Create();
            aes.Key = sha.ComputeHash(Encoding.UTF8.GetBytes(key)); // 32 bytes
            byte[] iv = new byte[aes.BlockSize / 8];
            Array.Copy(cipherBytes, 0, iv, 0, iv.Length);
            aes.IV = iv;
            using var ms = new MemoryStream();
            using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, iv.Length, cipherBytes.Length - iv.Length);
                cs.FlushFinalBlock();
            }
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
} 

VB.Net

Imports System.Security.Cryptography
Imports System.Text

Namespace WinFormsApp3
    Public Partial Class Form1
        Inherits Form
        Public Sub New()
            InitializeComponent()
        End Sub
        Private Sub btnEncrypt_Click(sender As Object, e As EventArgs)
            Dim encryptedText = EncryptPassword(txtInput.Text, "1234567")
            txtOutput.Text = encryptedText
        End Sub
        Private Sub btnDecrypt_Click(sender As Object, e As EventArgs)
            Dim decryptedText = DecryptPassword(txtInput.Text, "1234567")
            txtOutput.Text = decryptedText
        End Sub
        Private Function EncryptPassword(plaintext As String, key As String) As String
            Dim aes = Cryptography.Aes.Create()
            Dim sha = SHA256.Create()
            aes.Key = sha.ComputeHash(Encoding.UTF8.GetBytes(key)) ' 32 bytes
            aes.GenerateIV()

            Dim ms = New MemoryStream()
            ms.Write(aes.IV, 0, aes.IV.Length)
            Using cs = New CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)
                Dim data = Encoding.UTF8.GetBytes(plaintext)
                cs.Write(data, 0, data.Length)
                cs.FlushFinalBlock()
            End Using
            Return Convert.ToBase64String(ms.ToArray())
        End Function
        Private Function DecryptPassword(encryptedText As String, key As String) As String
            Dim cipherBytes = Convert.FromBase64String(encryptedText)
            Dim aes = Cryptography.Aes.Create()
            Dim sha = SHA256.Create()
            aes.Key = sha.ComputeHash(Encoding.UTF8.GetBytes(key)) ' 32 bytes
            Dim iv = New Byte(aes.BlockSize / 8 - 1) {}
            Array.Copy(cipherBytes, 0, iv, 0, iv.Length)
            aes.IV = iv
            Dim ms = New MemoryStream()
            Using cs = New CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write)
                cs.Write(cipherBytes, iv.Length, cipherBytes.Length - iv.Length)
                cs.FlushFinalBlock()
            End Using
            Return Encoding.UTF8.GetString(ms.ToArray())
        End Function
    End Class
End Namespace 

In above code I have I have generated two buttons click event one to encrypt the password and another to decrypt the provided password. In this I have defined two methods one is EncryptPassword(string plaintext, string key) and second one is DecryptPassword(string encryptedText, string key).  These methods have been called on respective button click event. In this method I have passed password and the secrete key.  

Here SHA256.Create() is a new instance in .net framework. This will create an instance of SHA256managed class if IFBB mode is not enabled. 

Now let's run the code check output. First, we will encrypt a password and after that we will decrypt the same password. Here one thing is important the secrete key is very important, it should be used same in both cases.

Encrypt Password

Here above we can see added password have been encrypted. Now let copy the same encrypted password and decrypt the give password.

Decrypt Password

Post a Comment