Encrypt and Decrypt Data with C#

In this blog I’m explaining how to encrypt or decrypt data with C#.


Encryption is the process of translating plain text data into something that appears random and meaning less.


Decryption is the process of translating random and meaningless data to plain text.

Why we need to use this Encryption and decryption processes. By using this process we can hide original data and display some junk data based on this we can provide some security for our data.

Here I will explain how to encrypt data and how to save that data into database after that I will show how to decrypt that encrypted data in database and how we can display that decrypted data on form.

I have a form with four fields username, password, first name, last name here I am encrypting password data and saving that data into database after that I am getting from database and decrypting the encrypted password data and displaying that data using grid view.



            Enter Text(Plain/Encrypt) <asp:TextBox ID="input_Text" runat="server"></asp:TextBox>

            Result <asp:TextBox ID="output_Text" runat="server"></asp:TextBox><br /><br /><br />

            <asp:Button ID="btnEncrypt" runat="server" Text="Encrypt" OnClick="btnEncrypt_Click" />

            <asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" OnClick="btnDecrypt_Click" />



Example: How to Encrypt Data in C#

protected void btnEncrypt_Click(object sender, EventArgs e)


        string strmsg = string.Empty;

        byte[] encode = new byte[input_Text.Text.Length];

        encode = Encoding.UTF8.GetBytes(input_Text.Text);

        strmsg = Convert.ToBase64String(encode);

        output_Text.Text = strmsg;


Make byte type array and set length of array equal to length of input string.

byte[] encode = new byte[input_Text.Text.Length];

Change the input string into ASCII values and set into byte type array.

encode = Encoding.UTF8.GetBytes(input_Text.Text);

Convert byte type array value using ToBase64String() method

strmsg = Convert.ToBase64String(encode);




Example: How to Decrypt Data in C#

protected void btnDecrypt_Click(object sender, EventArgs e)


        string decryptstring = string.Empty;

        UTF8Encoding encodestring = new UTF8Encoding();

        Decoder Decode = encodestring.GetDecoder();

        byte[] todecode_byte = Convert.FromBase64String(input_Text.Text);

        int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

        char[] decoded_char = new char[charCount];

        Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

        decryptstring = new String(decoded_char);

        output_Text.Text = decryptstring;



in my next post i'll explain about Introduction of Threading in C#

Leave Comment