Encryption of data is mandatory followed in some networks or in saving passwords to the database. So encrypting the data and decrypting the already encrypted code has been logged here.


Here there is two functions Encrypt and Decrypt to convert the data, find the below code for reference.



ASP.Net Code

<html>
<head runat="server">
    <title>Encrypt and Decrypt: fourthbottle</title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
  <table>
   <tr>
    <td>
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </td>
    <td>
     <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    </td>
   </tr>
   <tr>
    <td>
    <asp:Button ID="btnencrypt" runat="server" Text="Encrypt"
                        onclick="btnencrypt_Click" />
    </td>
    <td>
    <asp:Button ID="btndecrypt" runat="server" Text="Decrypt"
                        onclick="btndecrypt_Click" />
    </td>
   </tr>
  </table>
  </div>
  </form>
</body>
</html>

C# Code

using System;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;

namespace JSVirtualKeyboard
{
  public partial class WebForm2 : System.Web.UI.Page
   {

    private string Encrypt(string txttoEncrypt)
    {
        string EcriptedData = string.Empty;
        byte[] txt_encode = new byte[txttoEncrypt.Length];
        txt_encode = Encoding.UTF8.GetBytes(txttoEncrypt);
        EcriptedData = Convert.ToBase64String(txt_encode);
        return EcriptedData;
    }

    private string Decrypt(string txttoDecrypt)
    {
        UTF8Encoding encode_pwd = new UTF8Encoding();
        string DecryptedData = string.Empty;
        Decoder Decode = encode_pwd.GetDecoder();
        byte[] todecodeByte = Convert.FromBase64String(txttoDecrypt);
        int charCount = Decode.GetCharCount(
                                            todecodeByte,
                                            0,
                                            todecodeByte.Length
                                            );
        char[] decoded_char = new char[charCount];
        Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decoded_char, 0);
        DecryptedData = new String(decoded_char);
        return DecryptedData;
    }

    protected void btnencrypt_Click(object sender, EventArgs e)
    {
        TextBox2.Text = Encrypt(TextBox1.Text);
    }

    protected void btndecrypt_Click(object sender, EventArgs e)
    {
        TextBox1.Text = Decrypt(TextBox2.Text);
    }

  }
}