Thursday 9 August 2012

"Encrypt and Decrypt in asp.net for password field and also Login Code"

Procedure1 not Login Code


Cryptography.cs


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace QueryStringEncryption
{
    public static class Cryptography
    {
        #region Fields

        private static byte[] key = { };
        private static byte[] IV = { 38, 55, 206, 48, 28, 64, 20, 16 };
        private static string stringKey = "!5663a#KN";

        #endregion

        #region Public Methods

        public static string Encrypt(string text)
        {
            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] byteArray = Encoding.UTF8.GetBytes(text);

                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                    des.CreateEncryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();

                return Convert.ToBase64String(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return string.Empty;
        }

        public static string Decrypt(string text)
        {
            try
            {
                key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                Byte[] byteArray = Convert.FromBase64String(text);

                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                    des.CreateDecryptor(key, IV), CryptoStreamMode.Write);

                cryptoStream.Write(byteArray, 0, byteArray.Length);
                cryptoStream.FlushFinalBlock();

                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            //return string.Empty;
        }

        #endregion
    }
}

encryptdecrpt.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="encryptdecrpt.aspx.cs" Inherits="WebApplication1.encryptdecrpt" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1"
            runat="server" Text="Button" onclick="Button1_Click" />

            <br />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            EnableModelValidation="True" >
            <Columns>
             
                <asp:TemplateField HeaderText="Password">
                    <ItemTemplate>
                        <asp:TextBox ID="txtpass" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>

        </asp:GridView>
    </div>
    </form>
</body>
</html>

encryptdecrpt.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.Text;

namespace WebApplication1
{
    public partial class encryptdecrpt : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(@"Data Source=test;Initial Catalog=Demo;Integrated Security=True");
        DataSet ds = new DataSet();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                mfill();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            min(QueryStringEncryption.Cryptography.Encrypt(TextBox1.Text));
        }

        private void min(string pass)
    {
        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("Demoinsert", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@password", pass);
            cmd.ExecuteNonQuery();
            conn.Close();
        }
        catch (Exception ex) { throw new Exception(ex.Message); }
    }

        private void mfill()
        {
            SqlCommand cmd = new SqlCommand("select password from D", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);       
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();

            ((TextBox)(GridView1.Rows[0].Cells[0].FindControl("txtpass"))).Text = QueryStringEncryption.Cryptography.Decrypt(ds.Tables[0].Rows[0].ItemArray[0].ToString());

        }   
}
}



Procedure2 with Login Code

Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:TextBox ID="TextBox2"
            runat="server"></asp:TextBox><asp:Button ID="Button1" runat="server" 
            Text="Login" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


Login.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.Text;

public partial class Login : System.Web.UI.Page
{
    private const string strconneciton = "Data Source=SP2010;Initial Catalog=Demo;Integrated Security=True";
    SqlConnection con = new SqlConnection(strconneciton);

    protected void Page_Load(object sender, EventArgs e)
    {

    }


    private string Encryptdata(string password)
    {
        string strmsg = string.Empty;
        byte[] encode = new
        byte[password.Length];
        encode = Encoding.UTF8.GetBytes(password);
        strmsg = Convert.ToBase64String(encode);
        return strmsg;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            string strpassword = Encryptdata(TextBox2.Text);
            SqlCommand cmd = new SqlCommand("sp_Login", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("Name", TextBox1.Text);
            cmd.Parameters.Add("Password", strpassword);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {

                ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert(' Password & UserName Correct '); window.location.href = 'PasswordEncryption.aspx';", true);
                // Response.Redirect("HomeAdmin.aspx");  // throw a Exception
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", @"alert('Invalid Login Email & Password.');", true);
            }
         
        }
        catch (Exception ex) { throw new Exception(ex.Message); }
    }
}





PasswordEncryption.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PasswordEncryption.aspx.cs" Inherits="PasswordEncryption" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td>
    UserName
    </td>
    <td>
    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
    </td>
    </tr>
     <tr>
    <td>
    Password
    </td>
    <td>
    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
    </td>
    </tr>
     <tr>
    <td>
    FirstName
    </td>
    <td>
    <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
    </td>
    </tr>
      <tr>
    <td>
    LastName
    </td>
   
    </tr>
    <tr>
    <td>
    </td>
    <td>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
            onclick="btnSubmit_Click" />
    </td>
    </tr>
    </table>
    </div>
    <div>
    <asp:GridView ID="gvUsers" runat="server" CellPadding="4" ForeColor="#333333" 
            GridLines="None">
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
    </div>
    <div>
    <asp:Button ID="btnDecrypt" runat="server" Text="Decryption" 
            onclick="btnDecrypt_Click" /><br />
    <asp:GridView ID="gvdecryption" runat="server" BackColor="White" AutoGenerateColumns="false"
            BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" 
            onrowdatabound="gvdecryption_RowDataBound">
        <RowStyle BackColor="White" ForeColor="#330099" />
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="ID" />
            <asp:BoundField DataField="Name" HeaderText="Name" />
            <asp:BoundField DataField="Password" HeaderText="Password" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
        </Columns>
        <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
        <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
    </asp:GridView>
    </div>
    </form>
</body>
</html>



PasswordEncryption.aspx.cs



using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PasswordEncryption : System.Web.UI.Page
{

    private const string strconneciton = "Data Source=SP2010;Initial Catalog=Demo;Integrated Security=True";
  SqlConnection con = new SqlConnection(strconneciton);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindencryptedData();
            BindDecryptedData();
        }
    }
    /// <summary>
    /// btnSubmit event is used to insert user details with password encryption
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string strpassword = Encryptdata(txtPassword.Text);        
        con.Open();
        SqlCommand cmd = new SqlCommand("insert into ED(Name,Password,LastName) values('" + txtname.Text + "','" + strpassword + "','" + txtfname.Text + "')", con);     
        
        cmd.ExecuteNonQuery();
        con.Close();
        BindencryptedData();
        BindDecryptedData();
    }
    /// <summary>
    /// Bind user Details to gridview
    /// </summary>
    protected void BindencryptedData()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from ED", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvUsers.DataSource = ds;
        gvUsers.DataBind();
        con.Close();
    }
    /// <summary>
    /// Bind user Details to gridview
    /// </summary>
    protected void BindDecryptedData()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from ED", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvdecryption.DataSource = ds;
        gvdecryption.DataBind();
        con.Close();
    }
    /// <summary>
    /// Function is used to encrypt the password
    /// </summary>
   
    private string Encryptdata(string password)
    {
        string strmsg = string.Empty;
        byte[] encode = new
        byte[password.Length];
        encode = Encoding.UTF8.GetBytes(password);
        strmsg = Convert.ToBase64String(encode);
        return strmsg;
    }
    private string Decryptdata(string encryptpwd)
    {
        string decryptpwd = string.Empty;

            UTF8Encoding encodepwd = new UTF8Encoding();
            System.Text.Decoder utf8Decode = encodepwd.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
            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);
            decryptpwd = new String(decoded_char);
             return decryptpwd;
       
    }
    /// <summary>
    /// rowdatabound condition is used to change the encrypted password format to decryption format
    /// </summary>
   
    protected void gvdecryption_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType==DataControlRowType.DataRow)
        {
           
            string decryptpassword = e.Row.Cells[2].Text;
            e.Row.Cells[2].Text = Decryptdata(decryptpassword);

        }
    }
    /// <summary>
    /// btnDecrypt event is used to bind gridview with decryption of password
    /// </summary>
   
    protected void btnDecrypt_Click(object sender, EventArgs e)
    {
        BindDecryptedData();
    }
}


No comments:

Post a Comment