Home > Asp.net, C# Concept > How to encrypt and decrypt password in asp.net using C#?

How to encrypt and decrypt password in asp.net using C#?


Hi
Storing password in database as encrypted form is the good practice to store password. We can do this task using so many algorithms.

But here I m going to show you one of the easiest and complete secure method to encrypt and decrypt the password.

If you are storing password as encrypted formate using any algorithm without any salt value. Then hacker can easily decrypt the password using decryption method of same alogorith. But if you are using some salt value in your encrypted password then it will give completely strong encrtypted password.

Here we are mixing random salt value in encrtpted password.So It will be impossible to hack the data from database.

Here are some steps to do this tasks

Step1: Create one class i.e “Helper.cs” and write method like this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace Salt_Password_Sample
{
    public class Helper
    {

        public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
        {
            // If salt is not specified, generate it.
            if (saltBytes == null)
            {
                // Define min and max salt sizes.
                int minSaltSize = 4;
                int maxSaltSize = 8;

                // Generate a random number for the size of the salt.
                Random random = new Random();
                int saltSize = random.Next(minSaltSize, maxSaltSize);

                // Allocate a byte array, which will hold the salt.
                saltBytes = new byte[saltSize];

                // Initialize a random number generator.
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                // Fill the salt with cryptographically strong byte values.
                rng.GetNonZeroBytes(saltBytes);
            }

            // Convert plain text into a byte array.
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            // Allocate array, which will hold plain text and salt.
            byte[] plainTextWithSaltBytes =
            new byte[plainTextBytes.Length + saltBytes.Length];

            // Copy plain text bytes into resulting array.
            for (int i = 0; i < plainTextBytes.Length; i++)
                plainTextWithSaltBytes[i] = plainTextBytes[i];

            // Append salt bytes to the resulting array.
            for (int i = 0; i < saltBytes.Length; i++)
                plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
                hashAlgorithm = "";

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {

                case "SHA384":
                    hash = new SHA384Managed();
                    break;

                case "SHA512":
                    hash = new SHA512Managed();
                    break;

                default:
                    hash = new MD5CryptoServiceProvider();
                    break;
            }

            // Compute hash value of our plain text with appended salt.
            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

            // Create array which will hold hash and original salt bytes.
            byte[] hashWithSaltBytes = new byte[hashBytes.Length +
            saltBytes.Length];

            // Copy hash bytes into resulting array.
            for (int i = 0; i < hashBytes.Length; i++)
                hashWithSaltBytes[i] = hashBytes[i];

            // Append salt bytes to the result.
            for (int i = 0; i < saltBytes.Length; i++)
                hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

            // Convert result into a base64-encoded string.
            string hashValue = Convert.ToBase64String(hashWithSaltBytes);

            // Return the result.
            return hashValue;
        }

        public static bool VerifyHash(string plainText, string hashAlgorithm, string hashValue)
        {

            // Convert base64-encoded hash value into a byte array.
            byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

            // We must know size of hash (without salt).
            int hashSizeInBits, hashSizeInBytes;

            // Make sure that hashing algorithm name is specified.
            if (hashAlgorithm == null)
                hashAlgorithm = "";

            // Size of hash is based on the specified algorithm.
            switch (hashAlgorithm.ToUpper())
            {

                case "SHA384":
                    hashSizeInBits = 384;
                    break;

                case "SHA512":
                    hashSizeInBits = 512;
                    break;

                default: // Must be MD5
                    hashSizeInBits = 128;
                    break;
            }

            // Convert size of hash from bits to bytes.
            hashSizeInBytes = hashSizeInBits / 8;

            // Make sure that the specified hash value is long enough.
            if (hashWithSaltBytes.Length < hashSizeInBytes)
                return false;

            // Allocate array to hold original salt bytes retrieved from hash.
            byte[] saltBytes = new byte[hashWithSaltBytes.Length - hashSizeInBytes];

            // Copy salt from the end of the hash to the new array.
            for (int i = 0; i < saltBytes.Length; i++)
                saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];

            // Compute a new hash string.
            string expectedHashString = ComputeHash(plainText, hashAlgorithm, saltBytes);

            // If the computed hash matches the specified hash,
            // the plain text value must be correct.
            return (hashValue == expectedHashString);
        }

    }
}


Step2: Call that method in code behind file like this.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Salt_Password_Sample
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void EncryptBtn_Click(object sender, EventArgs e)
        {
            
            string EPass = Helper.ComputeHash(TextBox1.Text, "SHA512", null);
            lblmsg.Text = EPass;
        }

        
        protected void Button1_Click(object sender, EventArgs e)
        {
           bool flag = Helper.VerifyHash(TextBox1.Text, "SHA512", lblmsg.Text);
           if (flag == true)
           {
               lblmsg1.Text = "You are the correct user";
           }

                            
        }
    }
}

UserReg

If you are implementing this code with database then do like this,at insert time code will be like this


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 Salt_Password_Sample;

public partial class EmpReg : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    private void Cleartextbox()
    {
        txtAddress.Text = string.Empty;
        txtContactNo.Text = string.Empty;
        txtEmpName.Text = string.Empty;
        txtPassword.Text = string.Empty;
        txtUserId.Text = string.Empty;
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
        {
            using (SqlCommand cmd = new SqlCommand("Insert into tblLogin(UserId,Password,EmpName,Address,ContactNo) values(@UserId,@Password,@EmpName,@Address,@ContactNo)", con))
            {
                cmd.Parameters.AddWithValue("@UserId", txtUserId.Text);
                //Here i have implemented the code for doing encryption of password
                string ePass = Helper.ComputeHash(txtPassword.Text, "SHA512", null);

                cmd.Parameters.AddWithValue("@Password", ePass);
                cmd.Parameters.AddWithValue("@EmpName", txtEmpName.Text);
                cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
                cmd.Parameters.AddWithValue("@ContactNo", txtContactNo.Text);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                Cleartextbox();
                lblmsg.Text = "Your profile has been created Sucessfully";
            }
        }
        
    }
}

At login time,we have to write code like this, But make ensure that UserId should be unique in database


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 Salt_Password_Sample;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True"))
        {
            using(SqlCommand cmd=new SqlCommand("Select UserId,Password from tblLogin where UserId=@UserId",con))
            {
                cmd.Parameters.AddWithValue("@UserId", txtUserName.Text);
               
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                string userid = dt.Rows[0]["UserId"].ToString();
                string password=dt.Rows[0]["Password"].ToString();
                bool flag = Helper.VerifyHash(txtPassword.Text, "SHA512", password);

                if (userid == txtUserName.Text && flag == true)
                {
                    Response.Redirect("Welcome.aspx");
                }
                else
                {
                    lblmsg.Text = "Invalid UserId or password";
                }
                txtPassword.Text = string.Empty;
                txtUserName.Text = string.Empty;
            }
        }

    }
}

Forget Password

For forget password you can do like this.


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 Salt_Password_Sample;

public partial class ForgetPassword : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        string flag = CheckUserId();
        if (flag == "true")
        {
            using (SqlCommand cmd = new SqlCommand("update tblLogin set Password=@Password where UserId=@UserId", con))
            {
                cmd.Parameters.AddWithValue("@UserId", txtUserId.Text);
                //Here i have implemented the code for doing encryption of password
                string ePass = Helper.ComputeHash(txtPassword.Text, "SHA512", null);
                cmd.Parameters.AddWithValue("@Password", ePass);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                lblmsg.Text = "Your password has been Updated Sucessfully";
            }
        }
     
    }


    private string CheckUserId()
    {
        using (SqlCommand cmd = new SqlCommand("Select UserId from tblLogin where UserId=@UserId", con))
        {
            cmd.Parameters.AddWithValue("@UserId", txtUserId.Text);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count == 1)
            {
                
                return "true";
            }
            else
            {
                lblmsg.Text = "Invalid UserId";
                txtPassword.Text = string.Empty;
                return "false";
            }
           
        }
    }
   
}

Note:Before writting this article i read a lot on this topic.
I have tried to make completely secure code,But still if you think it is not a complete secure or hacker can hack the password, then fell free to share your idea.

You can download the code from here

About these ads
Categories: Asp.net, C# Concept
  1. kiran
    April 12, 2011 at 11:48 am

    thanks dude…. really encrypt and decrypt password in asp.net helped me a lot…

    • April 12, 2011 at 12:09 pm

      Hi

      You are always welcome. I will always post useful article like this.

  2. April 20, 2011 at 11:54 am

    It works for encryption not for decryption…….
    Error is occurred during decryption and error is
    catch (Exception ex)
    Line 63: {
    Line 64: throw new Exception(“Error in base64Decode” + ex.Message);
    Line 65: }
    Line 66:

  3. April 20, 2011 at 11:56 am

    base64DecodeInvalid length for a Base-64 char array.

  4. April 20, 2011 at 12:05 pm

    Hi

    Are you calling the decryption method like this

    string str = EncryptionTest.base64Decode(Label1.Text);
    Label2.Text = str;

  5. Shalini
    July 25, 2011 at 9:33 am

    hi i used

    string str = EncryptionTest.base64Decode(Label1.Text);
    Label2.Text = str;

    these to decrypt a value but it returns some symbols not the original pwd.is there is any more function missing?becoz u used GetChars right..its my doubt..plz help me

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

    • arun
      October 17, 2011 at 1:40 pm

      the problem is not with GetChars(), but with this piece of code, Convert.FromBase64String(sData), I guess

      Can you please mail me the source code.

      Thank you

      • October 17, 2011 at 5:05 pm

        Hi arun,

        I have sent the code to email Id. Please check it.

  6. July 25, 2011 at 4:09 pm

    Hi
    There is not missing any things. It is working perfect. I will send this code to your email id. You check it.

    • May 19, 2012 at 10:33 am

      Hi Chandra – thank a lot for your solution – its the best so far I’ve come across. Although I’m using VS2005, I have successfully used the code to store encryption anyway. However, I also have the same problem of error “Invalid lengthfor a Base-64 char array, at System.Convert.FromBase64String(String s)” when trying to decrypt. Could you send me solution. Thanks.

      • May 20, 2012 at 3:33 am

        Have you downloaded the latest code ? In latest code, i have not use the direct decryption process, i m using there some salt value.

        Could you tell me, when are you getting this error ?Please check the latest code. while testing in my system, i didnot get any error.

    • dinesh
      September 25, 2013 at 3:01 pm

      Can you send me the decryption code for the above example. it has only encryption code.

  7. anji
    September 14, 2011 at 1:00 pm

    hi,

    this code works for pwd 6 charecters only,
    if i want more than 6 char what can i do
    please help me

  8. September 15, 2011 at 2:18 pm

    Hi
    It should be work for more than 6 character. You can also see in screen shot.where i have used the name which is more than 6 char. Could you tell me what type of errors are you getting ?

  9. jeeya
    November 22, 2011 at 3:01 pm

    excellent…its working gr8
    thanks !

  10. arthur
    December 28, 2011 at 9:49 pm

    nice work. not only is it simple ,but it also easily use. thank you very much for your contribution.

    • December 29, 2011 at 3:57 am

      I m glad to know. You are welcome

  11. atik sarker
    January 1, 2012 at 5:05 am

    Thank you

  12. Sunny
    January 19, 2012 at 5:03 am

    Thank’s it’s working fine

  13. January 28, 2012 at 5:27 am

    Sure. I will send you.

  14. mohasina
    January 30, 2012 at 1:40 pm

    thanku

  15. Prakash.Kr
    February 6, 2012 at 11:43 am

    Nice Article

  16. Kavitha Prasanna
    February 13, 2012 at 1:36 pm

    Hi Thank you so much this is very usefull for all. Good Keep on your work…

    • February 13, 2012 at 5:20 pm

      You are welcome to my blog.I will try to keep on posting artical like this.

  17. T. Megana Nesalin Rose
    February 28, 2012 at 12:05 pm

    How I should save a encryoted password in a database. Can u please help me?

    Thank you,
    Megana

  18. T. Megana Nesalin Rose
    February 29, 2012 at 4:46 am

    Thanking You, for your code, and now how can i save this encrypted password in database table.

  19. T. Megana Nesalin Rose
    February 29, 2012 at 5:35 am

    Sorry, password has been encrypted and saved into database, but while i use this
    string str = EncryptionTest.base64Decode(Label1.Text);
    Label2.Text = str;, i couldn’t get the decrypted password from the database.

    • February 29, 2012 at 6:27 pm

      Hi
      Please download the code from share folder. I have also tested with database for you. Let me inform if you will get any problem.

  20. T. Megana Nesalin Rose
    February 29, 2012 at 5:35 am

    Sorry, password has been encrypted and saved into database, but while i use this
    string str = EncryptionTest.base64Decode(Label1.Text);
    Label2.Text = str;, i couldn’t get the decrypted password from the database.

  21. senthil
    February 29, 2012 at 3:10 pm

    Hi,

    this is senthil. when i have used in your decryption code i have error in (“Error in base64Decode” + ex.Message); “Error in base64DecodeInvalid length for a Base-64 char array.”. i want to just decrypt my password from my database table. please help me.

    • February 29, 2012 at 6:25 pm

      Hi friend,

      I m really sorry for late reply. Nowadays i m not free getting time for checking my mail and my blog.

      Since i got so many request from other person to upload code. So i m going to upload this code in my share folder. Please download from there.

  22. February 29, 2012 at 6:43 pm

    Hi friends,

    You can download my code from here. I have used VS2008 with inbuilt Sqlserver Express database.
    https://skydrive.live.com/?qt=shared&cid=4b1f6c3e92f6522c#cid=4B1F6C3E92F6522C&id=4B1F6C3E92F6522C!125

    Regards
    Chandradev

    • T. Megana Nesalin Rose
      March 1, 2012 at 4:36 am

      Hi Chandra Dev,

      Thank you, very much for your reply.

  23. T. Megana Nesalin Rose
    March 1, 2012 at 5:16 am

    Hi,

    I’m getting the decrypted password in a label, but I’m using a login page I want to login with the decrypted password in the textbox. But, the textbox is taking only the encrypted password. What can i do for this. I’m using Mysql connection. Waiting for you reply.

    • March 1, 2012 at 5:19 pm

      Hi @T. Megana Nesalin Rose, I have uploaded the exact code on basis of your request. But i have done with SQlServer and C#. Please download the code and check it. You have to only change connection string..

  24. senthil
    March 1, 2012 at 7:04 am

    Hi i got encrypt and decrypt password thanks boss.

  25. T. Megana Nesalin Rose
    March 2, 2012 at 4:42 am

    Hi,
    Thank you very much, I got it. Your article is very useful for us. Publish even more articles like this

  26. March 3, 2012 at 2:03 am

    Sure i will keep on sharing useful artical. Nowadays i m working on window based project so i m not getting time to write some artical. But i love web technology, in free time i used to keep on posting useful artical.

    • T. Megana Nesalin Rose
      March 3, 2012 at 5:20 am

      Hi,
      Can u send some examples about how to authenticate and authorize users for login page, which has roles such as admin and super admin. How can we set this in web.config file and coding for this.

      • March 3, 2012 at 10:23 am

        Hi @T. Megana Nesalin Rose, sure i will do. I have already tested code on that topic. I will share it.

  27. March 5, 2012 at 8:44 am

    hi Chandra,
    Hope u fine
    I want to build my own web service with encrypted soap header.
    Please help about this.
    I search many sites but there is not proper solution find.

    • March 6, 2012 at 1:12 am

      I m fine.Please give me some time,I will share artical on this topic.

  28. March 17, 2012 at 5:54 am

    Hi sir, hope u r doing great

    My requirement is to store the value of textbox into database in encypted format. I know how to save data in database using C#.net. But I don’t know how to encrypt the user data. Also I need to get the password in decrypted format too. How can I do that

    • March 18, 2012 at 1:30 pm

      Hi sir, Please download the code from my share folder and check it. I have used this concept. if you will get any problem then let me know.

  29. March 17, 2012 at 6:01 am

    hi sir, hope u r fine
    i inserted the multiple images by using grid view control. In database the images are stored in binary data format. i want to store in encrypted format. can u please help me out…..
    please view my code

    using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    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.Xml.Linq;
    using System.Data.SqlClient;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnupload_Click(object sender, EventArgs e)
    {
    if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != “”)
    {

    byte[] myimage = new byte[(FileUpload1.PostedFile.ContentLength)+1];
    byte[] myimage1 = new byte[(FileUpload2.PostedFile.ContentLength)+1];
    HttpPostedFile image = FileUpload1.PostedFile;
    image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);
    HttpPostedFile image1 = FileUpload2.PostedFile;
    image1.InputStream.Read(myimage1, 0, (int)FileUpload2.PostedFile.ContentLength);
    SqlConnection con = new SqlConnection(“Data Source=.;Initial Catalog=sample;User ID=sa;Password=123″);
    con.Open();
    SqlCommand cmd = new SqlCommand(“insert into tbl_multiple values(@ImageName,@Image,@Image1)”, con);
    cmd.Parameters.Add(“@ImageName”, txtimagename.Text);
    cmd.Parameters.Add(“@Image”, SqlDbType.Image, (myimage.Length)+1).Value = myimage;
    cmd.Parameters.Add(“@Image1″, SqlDbType.Image, (myimage1.Length)+1).Value = myimage1;

    cmd.ExecuteNonQuery();
    con.Close();
    }
    }
    protected void btnencrypt_Click(object sender, EventArgs e)
    {
    string val = txtimagename.Text;
    string pass = EncryptionTest.base64Encode(val);
    lblencrypt.Text = pass;
    }
    protected void btndecrypt_Click(object sender, EventArgs e)
    {
    string str = EncryptionTest.base64Decode(lbldecrypt.Text);
    lbldecrypt.Text = str;

    }
    }

    • March 18, 2012 at 1:47 pm

      Hi sir, I am fine.

      For storing multiple images in database as binary format is not a good approach in real project. If you will do like this, then loading of images will be very slow. If internet speed is slow, then you will also get exception error.

      For doing this type of task, we can store “Image URL” path in database and Images in “Images” folder. so at the time of loading, It will take only Image URL from database. So there will be no that much server overload.

      Here i don’t think any advantage to store image as encrypted format in database.It is not the sensitive data. If you want to protect the image for being download by other then we can do using other approach. Please let me know, what do you want to do ?

      Regards
      Chandradev

  30. March 19, 2012 at 4:26 am

    sir actually i am new to this .net recently i got a job. actually what ever the code i gave images are storing in binary data. but i have to store images in encrypt format.after completion then again i have to decrypt and retrieve the images this is want i want sir
    i hope u will give the best answer sir with coding
    and one more i want chating code sir…………….

  31. March 20, 2012 at 8:24 am

    thanku sir for giving me a reply .accepting as ur frnd and for suggestion also……..

    • March 23, 2012 at 12:09 pm

      Hi
      You are welcome. I also used to learn like you. I have updated my previous artical. It was not a good approach to do this task. Please check the latest code. It is so secure as compare to previous.

  32. Rama
    March 26, 2012 at 1:08 pm

    I am trying to enter this string to decode but not getting anything:

    “0FFAAE00-417D-49F6-98AA-C0CCEEBFE9F9″. Can you please decode?

    Thanks

  33. manoj
    March 27, 2012 at 2:24 pm

    thanks i got answer of my doubt.its good.

  34. sakshi
    March 28, 2012 at 6:39 pm

    the above encryption used is hashing????

    do u knw the code 4 auto sms???? …v want to add ds feature in our website…

    • March 29, 2012 at 5:47 pm

      Nowadays i m so busy in my new job. I cant open my blog in my office. Yes,this approach is not a complete secure.Please give me some time, i have to update my artical with complete secure code.

      For sending sms, you have to integrate “SMS API” in your project. The service provider company will give that “API Code” with sample. It will be very easy to integrate.But that will be payable service.

  35. Dhananjay Kumar
    March 29, 2012 at 3:19 pm

    Hi,
    Nice to read your blog i liked it.My question is that i am creating user using ASP.NET configuration tool and it saves user password in encrypted format but i am unable to decrypt the password from the above method as i am trying to implement forgot password functionality any idea or suggestion ??? for reference here is my code
    [HttpPost]
    public ActionResult Index(ForgotPassword obj)
    {
    var result = from password in DataContext.aspnet_Membership
    where password.Email == obj.Emailid
    select password.Password;
    foreach(string password in result)
    {
    pw = password;
    }
    if (pw != null)
    {
    FormsAuthenticationTicket Ftk = FormsAuthentication.Decrypt(pw);
    //It gives error at this line
    i am including using System.Web.Security; namespace

    Any ideas…………………………

    • March 29, 2012 at 5:49 pm

      Please give me some time to check your code.

    • March 29, 2012 at 5:49 pm

      Please give me some time to check your code.

  36. March 30, 2012 at 9:31 am

    hi sir how r u.hope u r doing great.
    sir i want in the given website the mouse cursor will be there know. when the cursor will move in webpage automatically the text should be also move with that cursor.For this i wnat java script please help me out as soon as possible. i hope u will sir……

    for example see the given below url u can know what ever the code i have wrriten above

    http://aipeukoraputdivision.blogspot.in/2010/07/new-symbol-of-indian-currency.html

  37. April 1, 2012 at 1:17 am

    Dear Sir,

    i m geting this error when im decrypting the password, please help me

    The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters.

    Source Error:

    Line 137: public static string Decrypt(string encryptedString)
    Line 138: {
    Line 139: FormsAuthenticationTicket Ftk = FormsAuthentication.Decrypt(encryptedString);
    Line 140: return Ftk.Name;
    Line 141: }

  38. Pavan124
    April 25, 2012 at 1:33 pm

    Nice Article.. Thanks you sir..

  39. Pavan124
    April 25, 2012 at 1:36 pm

    Regarding the error:valid Base-64 string as it contains a non-base 64 character,
    Even I have got the sam error,but i got to know the reaosn for that.
    The decryption algorythm works only for the encrypted data,If you try to decrypt a normal string it is returning the above error..

  40. May 1, 2012 at 3:06 pm

    Hi
    Please use the latest code of this artical.

    • mandy
      May 3, 2012 at 6:44 am

      Hi Chandra,
      I have tried this code but its not working with me,
      can you pl. tell me where is the latest code you have mentioned here.
      and if you please send me the code on my mail if posible

      id: naveen_bti@yahoo.com
      Thanks

      • May 5, 2012 at 1:41 am

        Hi i have uploaded the code in share folder. Please check it. If you get any problem then let me inform.

  41. Indra
    May 5, 2012 at 11:22 am

    GOod. It’s working nice. Thank you..

    • May 5, 2012 at 4:04 pm

      I glad to know that my artical helped you.

  42. fara
    May 17, 2012 at 4:28 am

    I have downloaded your file in your sky drive..there are 4 folders there..which 1 is the related one?

  43. May 18, 2012 at 1:38 pm

    thanks chandra dev its working fine

  44. Parag Parab (NetPP)
    May 30, 2012 at 11:21 am

    thanks dude It works fine…
    It help me to learn a lot

    • May 31, 2012 at 2:05 pm

      Nice to hear. I will try to write this type of artical.

  45. Vinay
    June 15, 2012 at 8:38 am

    Hi.. Very nice article… but decrypt is not working for me… Please send me the code for the decrypt the password.. I need to decrypt the password to match the password entered by the user from the password field… apologize for the errors or not understanding…

  46. June 17, 2012 at 5:39 am

    Hi
    Here we canot decrypt the password direcly. We are mixing salt value to make it strong. Please go throght the code and check the authentication concept.

  47. manojprabakaran
    June 20, 2012 at 11:24 am

    thanks for posted nice article,i done this as perfect but i can send single mail only i can’t send multiple mails at a time ,I have to write sp like
    use msdb

    GO
    EXEC sp_send_dbmail @profile_name=’Manojprabakaran’,
    @recipients=N’vadivelkarthick@gmail.com,manoj@icegen.net,karthick@icegen.net’,
    @subject=’Test message’,
    @body=’This is the body of the test message.
    Congrates Database Mail Received By you Successfully.’

    but mail would be send only first mail id,not an other …help me

  48. manigandan
    July 1, 2012 at 3:46 am

    please help me i want to store password as encrypted format and retrieve in oracle using asp.net send

    thank you

    • July 6, 2012 at 5:07 am

      Hi
      you can also apply this concept with oracle database. Here we are doing encryption process using C# code.

  49. Peterson
    July 12, 2012 at 6:48 pm

    Where is your Decrypt method?

    • July 16, 2012 at 9:17 am

      Hi
      Here we are not using direct decrypt process. We are adding some salt value for making the strong password

      • Peterson
        July 17, 2012 at 3:53 pm

        I need to be able to take the encrypted value and decrypt to plain text

  50. franc
    July 23, 2012 at 6:43 pm

    Hi dev. Nice post , but i tried your code which i downloaded from the link you gave, Whenever i clicked on encrypt button with the same password the encryptyed password keep changing, it is not giving the same encryption key is that correct?
    and how in case it is store in the database use it to Authenticate user, i tried to encrypt the passwrod and store it into the database and whenever user login encrypt the password he gave and compare it with the encrypted password stored but Not working, i dont know if i missed some steps ,am i doing it in right way or there is otherway?
    Please waiting for ur answer.
    thx.

  51. July 24, 2012 at 11:14 am

    Hi

    It is correct. Here we are mixing random salt value with encrypted password. So every time it will give different value. It has been done due to security purpose. For example somebody hacked you database and he want to decode your password then he may try to comparing the encrypted password.

    But if we will do like this, it will be impossible to guess and crack the password by hacker.

    I have done the authentication process without using database. You try to analysis the code and implement in your project. In my free time, i will integrate with database and i will share here.

  52. franc
    July 27, 2012 at 1:43 am

    Thanks dev got how to integrate it with my database. thanks a lot, great post, great article,easy to understand and well detailed, well commented, and like your implementation.

  53. TheGirlWho
    July 28, 2012 at 7:01 am

    Hey there! I have tried your code..
    thanks a lot! i have done the encryption and stored inside the database…
    now, the problem is the decryption part, i tried to do it but cannot…

    do u have a sample code where there is database on it? Thank you so much!! :)

  54. sanj
    August 12, 2012 at 3:34 pm

    Apologies, but I am using vb not c# do you have a vb version of your code?

    Thanks in advance

  55. Liji Sibin
    August 22, 2012 at 7:48 am

    Hi ChandraDev….Your article was very useful…..But i have no idea about decryption….Can you please send me the code for decryption…..The code for decryption is not there in your share folder. Your help will be greatly appreciated. Thankyou

    • September 1, 2012 at 1:57 am

      Hi
      Here we are not using direct decryption process.

  56. Aswad
    December 20, 2012 at 12:29 pm

    Hi Dev,
    Thank you so much for this code. great work.
    I have downloaded your code from skydrive.
    But i didn’t found any decryption method. Can you send on my email id ?
    BTW thanks.

    • December 20, 2012 at 6:46 pm

      Hi

      Please read the artical properly. Here we are not decrypting the password directly. if we will decrypt directly then here will be no security. Then anybody can hack the sensitive data. Please run the code and try to analyze the code.

  57. Anand
    January 23, 2013 at 9:00 pm

    Hi,
    I read your article it’s good. I need to encrypt and also decrypt confidential data. Is there any code so that I can use both rather than just using convert.tobase64 format?
    May not be a problem if doesn’t generate random number.

  58. March 5, 2013 at 9:04 am

    I was curious if you ever thought of changing the page layout of your blog?
    Its very well written; I love what youve got to say. But maybe
    you could a little more in the way of content so people
    could connect with it better. Youve got an awful lot of text for only having 1 or 2 images.

    Maybe you could space it out better?

    • March 5, 2013 at 9:11 am

      Thanks for your suggestion. I will do it in my free time.

  59. gaurav kapoor
    April 21, 2013 at 7:54 pm

    hello sir i want urgent need encypted code ….my reqment is when student is regsiter then automatically genrate the password and send it to student emailid ….i want tht password send in email but in encyptedmode and when student want decrypt the password first he/she enter the private key then password chnge the mode ..plz help me u can send me code

  60. April 23, 2013 at 11:40 pm

    Great beat ! I wish to apprentice while you amend your site,
    how can i subscribe for a blog website? The account aided me
    a acceptable deal. I had been a little bit acquainted
    of this your broadcast provided bright clear idea

  61. Astronaut77
    May 10, 2013 at 6:20 am

    Hi Everyone,
    I was trying to follow this Class, and what I have done is stored the password in SQL Data Base using the first method (ComputeHash), but when I tried to return the string stored in SQL DB and compare it to the string the user put it in a textBox, it is throwing and error in the method (VerifyHash) in the this line:
    byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
    Saying “Invalid length for a Base-64 char array.”
    Here is the code I used in both “adding the username and password” and retrieving username and password.
    //Encrypt Password
    string EPass = ComputeHash(textBox8.Text, “SHA512″, null);
    cmd = new SqlCommand(“Add_User_SP”, con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue(“@Username”, textBox7.Text.ToString().Trim());
    cmd.Parameters.AddWithValue(“@Password”, EPass);
    cmd.Parameters.AddWithValue(“@Email”, textBox10.Text.ToString().Trim());
    con.Open();
    int c = cmd.ExecuteNonQuery();

    if (c > 0)
    {
    con.Close();
    MessageBox.Show(“New User Inserted”, “Confirmation”, MessageBoxButtons.OK, MessageBoxIcon.Information);
    textBox7.Text = “”; textBox8.Text = “”; textBox9.Text = “”; textBox10.Text = “”; textBox11.Text = “”;

    }
    else

    MessageBox.Show(“Insertion Failed, try again”, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);
    con.Close();

    And here is the code for retrieving password and validate it against user input in the password textBox:

    string DB_Pass;
    //This variable “DB_Pass” is for passing the password from SQLDB and pass it to the VerifyHash method
    string EPass = ComputeHash(textBox2.Text, “SHA512″, null);
    cmd = new SqlCommand(“Login_SP_Encrypted”, con);
    cmd.Parameters.AddWithValue(“@Username”, textBox1.Text.ToString().Trim());
    cmd.CommandType = CommandType.StoredProcedure;
    con.Open();
    rdr = cmd.ExecuteReader();

    if (rdr.HasRows == true)
    {
    while (rdr.Read())
    {
    un = rdr["Username"].ToString();
    email = rdr["Email"].ToString();
    DB_Pass = rdr["Password"].ToString();

    }
    con.Close();
    }

    bool flag = VerifyHash(textBox2.Text, “SHA512″, DB_Pass);

    if (flag == true)
    {
    MessageBox.Show(“You are the correct user”);
    Form f2 = new Staff_Details_Form();
    this.Hide();
    f2.Show();

    }
    else
    MessageBox.Show(“Invalid Username Or Password!”, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);

    Any idea “Chandra Dev” why I’m getting that error and what should I do??!!

  62. May 18, 2013 at 2:11 pm

    Hi

    I have updated the artical, Please do like that. Now i hope that you can easily implement that code in your project.

    • astronaut77
      June 5, 2013 at 11:55 pm

      All good, found out that the database password column data type was the problem, I used to set it to nvarchar(50) and that won’t allow to take more than 50 char, and when the encrypted password was stored, it was more than 50 char, but when I changed that to nvarchar(Max), all working now.
      Thanks heaps for your help Chandra :)
      I just have 2 more question about app.config file.
      1- Is there anyway I can store and save to it (or update current value stored in it? Could you give an example code?
      2- How to make a form show for one time only with (Don’t show again) check box
      Thanks in advanced Chandra :)

  63. June 1, 2013 at 2:45 pm

    Hi to all, the contents existing at this site are in fact amazing for people knowledge,
    well, keep up the good work fellows.

    • June 1, 2013 at 5:10 pm

      Thanks for your kind word. I will keep on posting good artical like this.

  64. raheel
    June 5, 2013 at 8:28 am

    Not open in VS 2010 ur given code i download

    • June 5, 2013 at 5:23 pm

      Hi

      I have done using VS 2012. There would be one more code sample. Please download it.

      • rahul shah
        July 6, 2013 at 5:40 pm

        Sir your post is best for encrypt and decrypt password……it is very useful…………Will you plz provide me the code for retrieve forget password of hash password

  65. astronaut77
    June 6, 2013 at 12:06 am

    Hi Everyone,
    I just wanted to share what I found out about storing the encrypted password in the database and the “Invalid length for a Base-64 char array.” exception.
    Found out that you need to change the password column data type in the database to whatever it is to nvarchar(Max) or any other data type that contain such a long string as it is sometimes exceed the 90 char.
    I went step by step in code and found out when I was comparing the string that was generated and saved from the code to the one that was saved in the database and found out that it was missing lots of characters. :)

  66. rahul shah
    July 6, 2013 at 5:41 pm

    Sir your post is best for encrypt and decrypt password……it is very useful…………Will you plz provide me the code for retrieve forget password of hash password???

    • July 7, 2013 at 9:03 am

      Hi Rahul,

      I have already given option to download the code. Please download from there.

      • rahul shah
        July 7, 2013 at 2:42 pm

        sir i downloaded from website its works fine but i want to know how it works when user forgets the password, how to reset the old password or change the password….

  67. rahul shah
    July 7, 2013 at 2:45 pm

    sir i downloaded from website its works fine but i want to know how it works when user forgets the password, how to reset the old password or change the password….actually i am beginner in asp.net so plz provide me the code

  68. July 8, 2013 at 12:37 pm

    Dear Rahul

    On basis of your requirement, i have updated the artical and source code. Please check it and let me know if you will get any problem.

  69. rahul shah
    July 8, 2013 at 2:25 pm

    Sir you r genius,you solved my prob thanks sir your post are useful for beginners like me,,,,,i downloaded the code its works perfectly…
    Sir will you plz tell me how to forward reset link to reset forget password to user’s registered email id of hashed(salt) password

    • July 8, 2013 at 6:51 pm

      I m glad to know that my post helped you. Yes sending hashed code to user emailid is more secure as compare to directly change password on basis of emailId. In this approach also concept will be same. Firstly you have to send the one website URL + hashed code to that registered emailId and you have to also store that code in our table. if user will click on that URL then it will redirect to your website with that code.

      At page load time you can read that hashcode and validate in database.If this is the right user then give permission to reset password otherwise display invalid message.

  70. rahul shah
    July 9, 2013 at 3:49 pm

    hello sir i tried a lot to do so but i can’t get the right thing,,,sir i humbly requested to you plz provide the code to me on my email id(rahul06.it@gmail.com)

  71. rahul shah
    July 9, 2013 at 3:51 pm

    hello sir i tried a lot to do so but i can’t get the right thing,,,sir i humbly requested to you plz provide the code to me on my email id(rahul06.it@gmail.com)

    • July 9, 2013 at 5:31 pm

      I will send it. No problem.

      • rahul shah
        July 11, 2013 at 12:28 pm

        sir i haven’t received the code plz mail me………..

  72. July 14, 2013 at 7:54 pm

    Dear rahul, I have sent the code. Please check your inbox.

    • rahul shah
      July 16, 2013 at 2:09 pm

      thanks sir for responding……you rocksssss

  73. July 29, 2013 at 1:26 pm

    Hey there outstanding blog! Does running a blog such as this take a large amount of work?
    I’ve virtually no understanding of programming however I was hoping to start my own blog in the near future. Anyways, should you have any recommendations or techniques for new blog owners please share. I know this is off topic however I simply had to ask. Thank you!

  74. August 1, 2013 at 5:35 am

    Hello there! This is my first comment here
    so I just wanted to give a quick shout out and say I truly enjoy reading your posts.

    Can you suggest any other blogs/websites/forums that go over the
    same subjects? Thanks for your time!

  75. August 2, 2013 at 8:09 pm

    I don’t make it a habit to make comments on
    many articles, on that the other hand this one deserves attention.
    I agree with the data you have written so eloquently here.
    Thank you.

  76. August 4, 2013 at 6:32 am

    I’m not sure where you’re getting your information, but great topic.

    I needs to spend some time learning more or understanding more.

    Thanks for wonderful information I was looking for this
    information for my mission.

  77. rahul shah
    August 5, 2013 at 2:58 pm

    sir will you plz tell me how to convert .aspx page into PDF using C#……..

  78. rahul shah
    August 8, 2013 at 2:58 pm

    hello sir i tried a lot to convert “.aspx” to pdf but it throughs error such as illegal character in path.My requirement is when user fills the registration form and upload the photo through file upload tool after save the form then it save as in pdf format such as any competition form when we fill all the details and upload the photo then we save the forms(all the details) on clicking the “Save as PDF” such as in IBPS website..
    above link convert the webpage but If page contain any image control or file then How would we render it to PDF?
    so sir plz provide some solution to me………..

  79. rahul shah
    August 18, 2013 at 1:17 pm

    how to create ASP.net website compatible in all browsers

    • rahul shah
      August 18, 2013 at 4:59 pm

      sir i get the ans from your blog refer to topic cross browser compatibility
      but i want to know how to change login hyperlink to log out,i create login through programming ,i’m not using the login panel provided by the VS.net

      • September 9, 2013 at 3:05 pm

        Hi,

        For that you have to write code in code behind file. For example after login, you can change the text of linkbutton by C# code.

  80. Bryan
    August 26, 2013 at 8:33 am

    May i ask how do you do a forget password with email with the hash tag? Any reference? Regards.

  81. September 28, 2013 at 6:47 am

    Thanks for sharing your thoughts about indicative. Regards

  82. Mustaine
    November 17, 2013 at 7:50 pm

    Thanks alot Webmaster, usually I don’t left any comments in the web pages but this is amazing, at least for me as a newbie, I really appreciate it a bunch.

    My best whishes for you.

  83. April 21, 2014 at 6:49 pm

    I always spent my half an hour to read this webpage’s content every day along with a cup of coffee.

  84. April 21, 2014 at 7:54 pm

    Reblogged this on infotoinfo and commented:
    Good Knowledge blog.

  85. May 22, 2014 at 1:20 am

    You actually make it seem so easy with your presentation but I find this matter
    to be really something which I think I would never understand.
    It seems too complicated and extremely broad for me.
    I’m looking forward for your next post, I will try to get the hang of it!

  86. attorney
    May 27, 2014 at 2:18 am

    Hello! Someone in my Myspace group shared this site
    with us so I came to look it over. I’m definitely loving the information. I’m book-marking and will be tweeting
    this to my followers! Outstanding blog and amazing design.

  87. June 5, 2014 at 2:24 pm

    prada 2013
    Heya i am for the first time here. I came across
    this board and I find It truly useful & it helped me
    out a lot. I hope to give something back and aid others like you aided me.

  88. bharath
    July 14, 2014 at 5:32 pm

    Chandra Dev,

    Firstly, thanks for such an insightful article and i’m one of your follower.

    I ran into an issue with verifying the stored hash value.

    my stored string hashValue = “4Nhuu2LRLntxkUs8Nb0DzL84GRgi5AWhsf+fhfiy6BwTNiM9UUZSdFfWhkCond9hkBBZOA==”;

    and when i pass this to verifyHash method it converts into bytes using FromBase64String and that in turn yields to a bytes array of length 52. The problem comes when this length is compared to hashSizeInBytes, which is 64, and the latter being larger resulting in the false condition hence unable to proceed further.

    I’ve raised the same question in stackexchange : http://stackoverflow.com/questions/24728561/variable-is-bigger-than-byte-size-why

    Please go thru it in case i’ve not made myself clear with the description.

    • July 15, 2014 at 2:44 pm

      Hi

      Why are you using Base64 encode and decode approach. That is not a secure approach. In that approach hecker can easily heck your password. Please your some alogirthm with some salt value like SHA512.

      I have already created sample code using SHA512. Please use this in your application.

      • bharath
        July 15, 2014 at 5:57 pm

        Hi
        I used the same approach as you did. Infact i’m using the same code inside out. Problem, though, comes up when this piece of code picks up.
        if (hashWithSaltBytes.Length < hashSizeInBytes)
        return false;
        This results in false cause the hashvalue = “4Nhuu2LRLntxkUs8Nb0DzL84GRgi5AWhsf+fhfiy6BwTNiM9UUZSdFfWhkCond9hkBBZOA==”- which is a stored value in SQL- when converted into bytes(hashWithSaltBytes) it gives out rather 52 long byte array which in turn when put up a comparison against 64 size long hashSizeInBytes , leading to falsehood.

        Hope, it makes sense and this is where i need help.

        Bharath.

      • July 16, 2014 at 2:56 pm

        Hi
        could you please share your complete code with me. so that i can understand your exact problem.

      • bharath
        July 17, 2014 at 2:33 pm

        public static string ComputeHash(string plainText, string hashAlgorithm, byte[] saltBytes)
        {
        if (saltBytes == null)
        {
        int minSaltSize = 4;
        int maxSaltSize = 8;
        Random random = new Random();
        int saltSize = random.Next(minSaltSize, maxSaltSize);
        saltBytes = new byte[saltSize];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetNonZeroBytes(saltBytes);
        }

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
        for (int i = 0; i < plainTextBytes.Length; i++)
        plainTextWithSaltBytes[i] = plainTextBytes[i];
        for (int i = 0; i < saltBytes.Length; i++)
        plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];
        HashAlgorithm hash;
        if (hashAlgorithm == null)
        hashAlgorithm = "";
        switch (hashAlgorithm.ToUpper())
        {
        case "SHA384":
        hash = new SHA384Managed();
        break;
        case "SHA512":
        hash = new SHA384Managed();
        break;
        default:
        hash = new MD5CryptoServiceProvider();
        break;
        }
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
        byte[] hashWithSaltBytes = new byte[hashBytes.Length + saltBytes.Length];
        for (int i = 0; i < hashBytes.Length; i++)
        hashWithSaltBytes[i] = hashBytes[i];
        for (int i = 0; i < saltBytes.Length; i++)
        hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);
        return hashValue;

        }
        //using the above method i got the plain text "qwerty" converted to hashValue and have it stored in DB. Now when user enters the password the below method puts up the comparison with the hashValue and decides if the user is authentic. Is what I understand. Now the problem comes up when I run this piece of code as it results to false. if (hashwithSaltBytes.Length < hashSizeInBytes)
        return false;
        The problem, like i stated earlier, the comparison is between 52 sixe byte array and 64 size byte array. As 52<64, leading to false.

        public static bool VerifyHash(string plainText, string hashAlgorithm, string hashValue)
        {
        byte[] hashwithSaltBytes = Convert.FromBase64String(hashValue);
        int hashSizeInBytes, hashSizeInBits;
        if (hashAlgorithm == null)
        hashAlgorithm = "";
        switch (hashAlgorithm.ToUpper())
        {
        case "SHA384":
        hashSizeInBits = 384;
        break;
        case "SHA512":
        hashSizeInBits = 512;
        break;
        default:
        hashSizeInBits = 128;
        break;
        }
        hashSizeInBytes = hashSizeInBits / 8;
        if (hashwithSaltBytes.Length < hashSizeInBytes)
        return false;
        byte[] saltBytes = new byte[hashwithSaltBytes.Length - hashSizeInBytes];
        for (int i = 0; i < saltBytes.Length; i++)
        saltBytes[i] = hashwithSaltBytes[hashSizeInBytes + i];
        string expectedString = ComputeHash(plainText, hashAlgorithm, saltBytes);
        return (expectedString == hashValue);
        }

  89. July 20, 2014 at 9:36 am

    Hi
    Sorry for late reply. I had already share the sample application using this algorithm in my skydrive. have you downloaded and tested the code in your system ?

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 50 other followers

%d bloggers like this: