Encrypt and Decrypt Strings in C#.Net & VB.NET With a Secret Key

How to security encrypt and descript string using c#.net and vb.net using security key. This tutorial has best practice for data protection.
In today's article I will show you how you can encrypt and decrypt a string value in c#.net and VB.NET with serrate key. Here i am using CryptoStream to encrypt the plain text. This tutorial will demonstrate a perfect example of C# AES Encrypt Decrypt example, 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. 

Form Design

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 = Encrypt(txtInput.Text, "1234567");
            txtOutput.Text = encryptedText;
        }
       
        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            string decryptedText = Decrypt(txtInput.Text, "1234567");
            txtOutput.Text = decryptedText;
        }
        private string Encrypt(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 Decrypt(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 = Encrypt(txtInput.Text, "1234567")
            txtOutput.Text = encryptedText
        End Sub
        Private Sub btnDecrypt_Click(sender As Object, e As EventArgs)
            Dim decryptedText = Decrypt(txtInput.Text, "1234567")
            txtOutput.Text = decryptedText
        End Sub
        Private Function Encrypt(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 Decrypt(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 plain text and another to decrypt the provided text. In this i have defined two methods one is Encrypt(string plaintext, string key) and second one is Decrypt(string encryptedText, string key).  These methods have been called on respective button click event. In this method I have passed text 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 plain text and after that we will decrypt the same text. Here one thing is important the secrete key is very important, it should be used same in both cases.

Encrypt Text

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

Decrypt Text

Post a Comment