Store Password in Encrypted format to Database in asp.net - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

Store Password in Encrypted format to Database in asp.net

Introduction: In this article I have explain how we can insert the password in encrypted format to database.
 encrypted password

Description:

I created a Table USER_REGISTRATION:
ID
int
USERNAME
varchar(50)
PASSWORD
varchar(50)
FIRST_NAME
varchar(50)
LAST_NAME
varchar(50)
SEX
varchar(50)
PHONE
int
EMAIL_ID
varchar(50)

Here ID is autoincrement and primary key.
Add a webform to project. Drag and drop the controls Textbox, button from Toolbox and design the page show below:
<div class="form">
    <table>
    <tr><td>Username:-</td><td>
        <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
      
        </td></tr>
        <tr><td>First Name:-</td><td>
            <asp:TextBox ID="txtfirst" runat="server"></asp:TextBox></td></tr>
            <tr><td>Last Name:-</td><td>
                <asp:TextBox ID="txtlast" runat="server"></asp:TextBox></td></tr>
                               <tr><td>Sex:-</td><td>
                    <asp:RadioButtonList ID="rblsex" runat="server">
                        <asp:ListItem>Male</asp:ListItem>
                        <asp:ListItem>Female</asp:ListItem>
                    </asp:RadioButtonList>
                </td></tr>
                 <tr><td>Phone:-</td><td>
                <asp:TextBox ID="txtphone" runat="server"></asp:TextBox></td></tr>
                <tr><td>Email Id:-</td><td><asp:TextBox ID="txtemail" 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>Confirm Password:-</td><td>
                            <asp:TextBox ID="txtconfirm" runat="server" TextMode="Password"></asp:TextBox></td></tr>
                                                         <tr>
                                   <td>&nbsp;</td><td>
                                       <asp:Button ID="btnsave" runat="server" Text="Save" onclick="btnsave_Click" />
                                      </td>
                                    </tr>
    </table>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
    </div>

After that keep the below given Jquery in between Head Tag to validate the textboxes:
<link href="css/style.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.validate.css" rel="stylesheet" type="text/css" />
    <script src="js/jquery-1.6.4.js" type="text/javascript"></script>
    <script src="js/jquery.validate.js" type="text/javascript"></script>
    <script src="js/jquery.validation.functions.js" type="text/javascript"></script>
      <script type="text/javascript">
            jQuery(function(){
                jQuery("#txtusername").validate({
                    expression: "if (VAL) return true; else return false;",
                    message: "Enter Username"
                });
                 jQuery("#txtfirst").validate({
                    expression: "if (VAL) return true; else return false;",
                    message: "Enter First Name"
                });
                 jQuery("#txtlast").validate({
                    expression: "if (VAL) return true; else return false;",
                    message: "Enter Last Name"
                });
                jQuery("#txtemail").validate({
                    expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
                    message: "Enter valid Email id"
                });
                jQuery("#rblsex").validate({
                    expression: "if (isChecked(SelfID)) return true; else return false;",
                    message: "Check atleast one checkbox"
                });
                jQuery("#").validate({
                    expression: "if (VAL.match(/^[9][0-9]{9}$/)) return true; else return false;",
                    message: "Enter valid Mobile Number"
                });
                 jQuery("#txtphone").validate({
                    expression: "if (!isNaN(VAL) && VAL) return true; else return false;",
                    message: "Should be a number"
                });
               jQuery("#txtpassword").validate({
                    expression: "if (VAL.length > 5 && VAL) return true; else return false;",
                    message: "Enter a valid Password atleast 6 character"
                });
                jQuery("#txtconfirm").validate({
                    expression: "if ((VAL == jQuery('#txtpassword').val()) && VAL) return true; else return false;",
                    message: "Confirm password field doesn't match the password field"
                });
            });
        </script>

To download Stylesheet and Jquery Click Here.
After that on button click write the below given code (.aspx.cs):
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Text;
using System.IO;
using System.Security.Cryptography;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());

protected void btnsave_Click(object sender, EventArgs e)
    {
        try
        {
            string encryptpassword = EncryptPasswordString(txtpassword.Text);
                string query = "insert into USER_REGISTRATION (USERNAME,FIRST_NAME,LAST_NAME,SEX,EMAIL_ID,PHONE,PASSWORD) values('" + txtusername.Text.Trim() + "','" + txtfirst.Text.Trim() + "','" + txtlast.Text.Trim() + "','" + rblsex.SelectedValue + "','" + txtemail.Text + "','"+txtphone.Text+"','" + encryptpassword + "')";
                SqlCommand cmd = new SqlCommand(query, con);
                con.Open();
                cmd.ExecuteNonQuery();
                Clear();
                Messagebox("Successfully Register");           
        }
        catch (Exception ex)
        {
        }
    }
    private void Messagebox(string Message)
    {
        Label lblMessageBox = new Label();
        lblMessageBox.Text =
            "<script language='javascript'>" + Environment.NewLine +
            "window.alert('" + Message + "')</script>";
        Page.Controls.Add(lblMessageBox);
    }
    public void Clear()
    {
        txtusername.Text = "";
        txtfirst.Text = "";
        txtlast.Text = "";
        txtemail.Text = "";
        txtpassword.Text = "";
        txtconfirm.Text = "";
        txtphone.Text = "";
        rblsex.SelectedIndex = -1;
    }
//Encrypt Password
    public string EncryptPasswordString(string inputString)
    {
        MemoryStream memStream = null;
        try
        {
            byte[] key = { };
            byte[] IV = { 12, 21, 43, 17, 57, 35, 67, 27 };
            string encryptKey = "aXb2uy4z";
            key = Encoding.UTF8.GetBytes(encryptKey);
            byte[] byteInput = Encoding.UTF8.GetBytes(inputString);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            memStream = new MemoryStream();
            ICryptoTransform transform = provider.CreateEncryptor(key, IV);
            CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write);
            cryptoStream.Write(byteInput, 0, byteInput.Length);
            cryptoStream.FlushFinalBlock();

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        return Convert.ToBase64String(memStream.ToArray());
    }

In VB (.aspx.vb)
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Connection").ToString())

    Protected Sub btnsave_Click(sender As Object, e As System.EventArgs) Handles btnsave.Click
        Try
            Dim encryptpassword As String = EncryptPasswordString(txtpassword.Text)
            Dim query As String = ((("insert into USER_REGISTRATION (USERNAME,FIRST_NAME,LAST_NAME,SEX,EMAIL_ID,PHONE,PASSWORD) values('" & txtusername.Text.Trim() & "','" & txtfirst.Text.Trim() & "','" & txtlast.Text.Trim() & "','") + rblsex.SelectedValue & "','") + txtemail.Text & "','") + txtphone.Text & "','" & encryptpassword & "')"
            Dim cmd As New SqlCommand(query, con)
            con.Open()
            cmd.ExecuteNonQuery()
            Clear()
            Messagebox("Successfully Register")
        Catch ex As Exception
        End Try
    End Sub
    Private Sub Messagebox(ByVal Message As String)
        Dim lblMessageBox As New Label()
        lblMessageBox.Text = "<script language='javascript'>" + Environment.NewLine & "window.alert('" & Message & "')</script>"
        Page.Controls.Add(lblMessageBox)
    End Sub
    Public Sub Clear()
        txtusername.Text = ""
        txtfirst.Text = ""
        txtlast.Text = ""
        txtemail.Text = ""
        txtpassword.Text = ""
        txtconfirm.Text = ""
        txtphone.Text = ""
        rblsex.SelectedIndex = -1
    End Sub
'Encrypt Password
    Public Function EncryptPasswordString(ByVal inputString As String) As String
        Dim memStream As MemoryStream = Nothing
        Try
            Dim key As Byte() = {}
            Dim IV As Byte() = {12, 21, 43, 17, 57, 35, _
             67, 27}
            Dim encryptKey As String = "aXb2uy4z"
            key = Encoding.UTF8.GetBytes(encryptKey)
            Dim byteInput As Byte() = Encoding.UTF8.GetBytes(inputString)
            Dim provider As New DESCryptoServiceProvider()
            memStream = New MemoryStream()
            Dim transform As ICryptoTransform = provider.CreateEncryptor(key, IV)
            Dim cryptoStream As New CryptoStream(memStream, transform, CryptoStreamMode.Write)
            cryptoStream.Write(byteInput, 0, byteInput.Length)

            cryptoStream.FlushFinalBlock()
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
        Return Convert.ToBase64String(memStream.ToArray())
    End Function

Build and run the project. Now you see in the Database Password is Store in Encrypted format like bsTes+zwUwI=, M7O9mojeM24= .

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+

4 comments

nice . this site is very helpful.
thanks vijay

thanks for appreciation Ritesh. Stayed connected for more articles....

thanks !!!!! :)!! more tutorials please.. :)! you're great !!

thanks jean... keep reading... new post
http://www.articlemirror.in/2015/08/how-to-show-confirmation-alert-before-closing-browser-javascript.html


EmoticonEmoticon