Encryption and Decryption in C#

Encryption & Decryption in C#

                   In this blog I’m explaining how to encrypt or decrypt data with C#.
Encryption:
Encryption is the process of translating plain text data into something that appears random and meaningless to the others.
Decryption:
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 three fields id, username, password and 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.
Here are steps how to use Random password in our application.
1.    First design one table “tbl_Login” in your database like as shown bellow-



For this, We have added a new page in our application then use the following code-
Default.ASPX Html View
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width100%;
        }
        .style2
        {
            width170px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <table class="style1">
            <tr>
                <td class="style2">
                    User Name
                </td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server" Width="200px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Password</td>
                <td>
                    <asp:TextBox ID="txtPassword" runat="server" Width="200px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Btn_Submit" runat="server" Text="Submit"
                        onclick="Btn_Submit_Click" />
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    <asp:Label ID="lblmsg" runat="server" Text=""></asp:Label>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    <asp:GridView ID="GridView1" runat="server">
                    </asp:GridView>
                </td>
            </tr>
        </table>
   
    </div>
    </form>
</body>
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
    string ConnectionString = "Data Source=MY-PC;Initial Catalog=Test;User ID=sa;Password=abc";
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConnectionString);
        getLoginDetails();
    }
    protected void Btn_Submit_Click(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
       using(SqlCommand cmd=new SqlCommand("INSERT INTO tbl_Login(UserName,Password)VALUES(@UserName,@Password)",con))
       {
           cmd.Parameters.Add("@UserName"SqlDbType.NVarChar).Value = txtUserName.Text;
           cmd.Parameters.Add("@Password"SqlDbType.NVarChar).Value =Encrypt(txtPassword.Text);
           cmd.ExecuteNonQuery();
       }
    }
    public static string Encrypt(string password)
    {
        try
        {
            byte[] encData_byte = new byte[password.Length];
            encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
            string encodedData = Convert.ToBase64String(encData_byte);
            return encodedData;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Encode" + ex.Message);
        }
    }
    public string Decrypt(string encodedData)
    {
        System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
        System.Text.Decoder utf8Decode = encoder.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(encodedData);
        int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[charCount];
        utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        string result = new String(decoded_char);
        return result;
    }
    private void getLoginDetails()
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        using(SqlDataAdapter adpt=new SqlDataAdapter("SELECT UserName,Password From tbl_Login",con))
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("UserName");
            dt.Columns.Add("Password");
            string UserName = "";
            string Password = "";
            DataTable dt1 = new DataTable();
            adpt.Fill(dt1);
            if(dt1.Rows.Count>0)
            {
                UserName = dt1.Rows[0][0].ToString();
                Password = Decrypt(dt1.Rows[0][1].ToString());
                dt.Rows.Add(UserName, Password);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }
}

Screen shots of the Applciation-




Download Source Code: Click Here
written by - Ravi Kumar Soni




No comments:

Post a Comment