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

Advertisement

186 thoughts on “How to encrypt and decrypt password in asp.net using C#?

  1. kiran April 12, 2011 / 11:48 am

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

    • Chandra Dev April 12, 2011 / 12:09 pm

      Hi

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

      • Pratik May 3, 2015 / 6:33 am

        Hi Chandra,

        I was really looking for the encryption deception code to use in my website. could you please send me the source of this. It will be really very helpful.
        thanks.

  2. Dhanashri April 20, 2011 / 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. Dhanashri April 20, 2011 / 11:56 am

    base64DecodeInvalid length for a Base-64 char array.

  4. Chandra Dev April 20, 2011 / 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 / 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 / 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

      • Chandra Dev October 17, 2011 / 5:05 pm

        Hi arun,

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

  6. Chandra Dev July 25, 2011 / 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.

    • John Chagbert May 19, 2012 / 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.

      • Chandra Dev May 20, 2012 / 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 / 3:01 pm

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

    • Akruti Singh August 26, 2021 / 4:09 am

      can you please send to me also

  7. anji September 14, 2011 / 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. Chandra Dev September 15, 2011 / 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 / 3:01 pm

    excellent…its working gr8
    thanks !

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

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

    • Chandra Dev December 29, 2011 / 3:57 am

      I m glad to know. You are welcome

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

    Thank you

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

    Thank’s it’s working fine

  13. mohasina January 30, 2012 / 1:40 pm

    thanku

  14. Prakash.Kr February 6, 2012 / 11:43 am

    Nice Article

  15. Kavitha Prasanna February 13, 2012 / 1:36 pm

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

    • Chandra Dev February 13, 2012 / 5:20 pm

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

  16. T. Megana Nesalin Rose February 28, 2012 / 12:05 pm

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

    Thank you,
    Megana

  17. T. Megana Nesalin Rose February 29, 2012 / 4:46 am

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

  18. T. Megana Nesalin Rose February 29, 2012 / 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.

    • Chandra Dev February 29, 2012 / 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.

  19. T. Megana Nesalin Rose February 29, 2012 / 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.

  20. senthil February 29, 2012 / 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.

    • Chandra Dev February 29, 2012 / 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.

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

      Hi Chandra Dev,

      Thank you, very much for your reply.

  21. T. Megana Nesalin Rose March 1, 2012 / 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.

    • Chandra Dev March 1, 2012 / 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..

  22. senthil March 1, 2012 / 7:04 am

    Hi i got encrypt and decrypt password thanks boss.

  23. T. Megana Nesalin Rose March 2, 2012 / 4:42 am

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

  24. Chandra Dev March 3, 2012 / 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 / 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.

      • Chandra Dev March 3, 2012 / 10:23 am

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

  25. Farrukh March 5, 2012 / 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.

    • Chandra Dev March 6, 2012 / 1:12 am

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

  26. K.Lohith Kumar March 17, 2012 / 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

    • Chandra Dev March 18, 2012 / 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.

  27. K.Lohith Kumar March 17, 2012 / 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;

    }
    }

    • Chandra Dev March 18, 2012 / 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

  28. K.Lohith Kumar March 19, 2012 / 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…………….

  29. lohith kumar March 20, 2012 / 8:24 am

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

    • Chandra Dev March 23, 2012 / 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.

  30. Rama March 26, 2012 / 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

  31. manoj March 27, 2012 / 2:24 pm

    thanks i got answer of my doubt.its good.

  32. sakshi March 28, 2012 / 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…

    • Chandra Dev March 29, 2012 / 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.

  33. Dhananjay Kumar March 29, 2012 / 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…………………………

    • Chandra Dev March 29, 2012 / 5:49 pm

      Please give me some time to check your code.

    • Chandra Dev March 29, 2012 / 5:49 pm

      Please give me some time to check your code.

  34. K.Lohith Kumar March 30, 2012 / 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

  35. krishna April 1, 2012 / 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: }

  36. Pavan124 April 25, 2012 / 1:33 pm

    Nice Article.. Thanks you sir..

  37. Pavan124 April 25, 2012 / 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..

  38. Chandra Dev May 1, 2012 / 3:06 pm

    Hi
    Please use the latest code of this artical.

    • mandy May 3, 2012 / 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

      • Chandra Dev May 5, 2012 / 1:41 am

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

  39. Indra May 5, 2012 / 11:22 am

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

    • Chandra Dev May 5, 2012 / 4:04 pm

      I glad to know that my artical helped you.

  40. fara May 17, 2012 / 4:28 am

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

  41. pitambar May 18, 2012 / 1:38 pm

    thanks chandra dev its working fine

  42. Parag Parab (NetPP) May 30, 2012 / 11:21 am

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

    • Chandra Dev May 31, 2012 / 2:05 pm

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

  43. Vinay June 15, 2012 / 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…

  44. Chandra Dev June 17, 2012 / 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.

  45. manojprabakaran June 20, 2012 / 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

  46. manigandan July 1, 2012 / 3:46 am

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

    thank you

    • Chandra Dev July 6, 2012 / 5:07 am

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

  47. Peterson July 12, 2012 / 6:48 pm

    Where is your Decrypt method?

    • Chandra Dev July 16, 2012 / 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 / 3:53 pm

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

  48. franc July 23, 2012 / 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.

  49. Chandra Dev July 24, 2012 / 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.

  50. franc July 27, 2012 / 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.

  51. TheGirlWho July 28, 2012 / 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!! 🙂

  52. sanj August 12, 2012 / 3:34 pm

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

    Thanks in advance

  53. Liji Sibin August 22, 2012 / 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

    • Chandra Dev September 1, 2012 / 1:57 am

      Hi
      Here we are not using direct decryption process.

  54. Aswad December 20, 2012 / 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.

    • Chandra Dev December 20, 2012 / 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.

  55. Anand January 23, 2013 / 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.

  56. Bertie March 5, 2013 / 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?

    • Chandra Dev March 5, 2013 / 9:11 am

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

  57. gaurav kapoor April 21, 2013 / 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

  58. Grimm Tv Series Season 2 April 23, 2013 / 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

  59. Astronaut77 May 10, 2013 / 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??!!

  60. Chandra Dev May 18, 2013 / 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 / 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 🙂

  61. building self awareness June 1, 2013 / 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.

    • Chandra Dev June 1, 2013 / 5:10 pm

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

  62. raheel June 5, 2013 / 8:28 am

    Not open in VS 2010 ur given code i download

    • Chandra Dev June 5, 2013 / 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 / 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

  63. astronaut77 June 6, 2013 / 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. 🙂

  64. rahul shah July 6, 2013 / 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???

    • Chandra Dev July 7, 2013 / 9:03 am

      Hi Rahul,

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

      • rahul shah July 7, 2013 / 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….

  65. rahul shah July 7, 2013 / 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

  66. Chandra Dev July 8, 2013 / 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.

  67. rahul shah July 8, 2013 / 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

    • Chandra Dev July 8, 2013 / 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.

  68. rahul shah July 9, 2013 / 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)

  69. rahul shah July 9, 2013 / 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)

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

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

  70. Chandra Dev July 14, 2013 / 7:54 pm

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

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

      thanks sir for responding……you rocksssss

  71. amateur lesbians licking movies tube July 29, 2013 / 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!

  72. scholarships August 1, 2013 / 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!

  73. payday loans online August 2, 2013 / 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.

  74. tablette graphique dessin August 4, 2013 / 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.

  75. rahul shah August 5, 2013 / 2:58 pm

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

  76. rahul shah August 8, 2013 / 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………..

  77. rahul shah August 18, 2013 / 1:17 pm

    how to create ASP.net website compatible in all browsers

    • rahul shah August 18, 2013 / 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

      • Chandra Dev September 9, 2013 / 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.

  78. Bryan August 26, 2013 / 8:33 am

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

  79. "incident" September 28, 2013 / 6:47 am

    Thanks for sharing your thoughts about indicative. Regards

  80. Mustaine November 17, 2013 / 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.

  81. Option Binaire May 22, 2014 / 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!

  82. attorney May 27, 2014 / 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.

  83. prada 2013 June 5, 2014 / 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.

  84. bharath July 14, 2014 / 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.

    • Chandra Dev July 15, 2014 / 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 / 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.

      • Chandra Dev July 16, 2014 / 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 / 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);
        }

  85. Chandra Dev July 20, 2014 / 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 ?

  86. 04Matt04 July 26, 2014 / 4:45 am

    Pretty nice post. I just stumbled upon your weblog and wanted to say that
    I’ve truly enjoyed surfing around your blog posts.
    In any case I’ll be subscribing to your rss feed and I hope you write again soon!

  87. skko August 1, 2014 / 7:24 am

    Hi, chandradev,
    I still got error to decrypt , Encryption is ok. but decrypt is problem, in verifyHash method

    Invalid length for a Base-64 char array or string.
    byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

    I tried your code that attached in this article,
    pls help me.

    regards

  88. Cromwell September 2, 2014 / 5:50 pm

    Very good example. I’ve been looking for a good way to hash some text and store it in a database. This is the best way I’ve seen so far for C Sharp and you made it very easy to understand. Thanks!

    • Chandra Dev September 4, 2014 / 1:54 pm

      I am glad to know that you liked it.

  89. www.fcdtf.com September 6, 2014 / 12:02 am

    Excellent post. I was checking constantly this blog and I’m impressed!
    Extremely useful info specially the last part 🙂 I care for such info much.

    I was seeking this particular information for a long time.
    Thank you and good luck.

    • Chandra Dev September 9, 2014 / 3:33 am

      Thank you for posting sweet feedback.

  90. karthikeyan September 8, 2014 / 11:07 am

    one of the best examples for encryption and decryption. Thank you buddy

    • Chandra Dev September 9, 2014 / 3:34 am

      I am glad to know that you liked it.

  91. cleopatrame October 2, 2014 / 7:37 pm

    Pretty nice post. I just stumbled upon your weblog
    and wanted to say that I’ve really enjoyed browsing your blog posts.
    In any case I’ll be subscribing to your feed and I hope you write again very soon!

  92. pramod December 29, 2014 / 12:51 pm

    Hello sir,
    BUT HOW WE CAN DECRYPT MY STRING
    IN THIS ARTICLE EXPLAIN ONLY VERIFY STRING
    I WANT TO DECRYPT MY STRING .

    • Chandra Dev February 19, 2015 / 8:13 am

      you canot decrypt the password. If you will decrypt the password to original formate. Then there will be security problem. Developer can easily decode the sensitive password from database.

  93. Dhanashree February 6, 2015 / 1:20 pm

    Hi Chandra ,I am quite new to c# coding… I want to encrypt a password using SHA-256 algorithm using user salt string or without user salt string in asp.net c# . can you please send me the code or full example how to implement this in .net (both aspx and c#) on this mail id – dhanashri.dbd@gmail.com

    • Dhanashree February 6, 2015 / 1:29 pm

      Also please tell me how to produce generate user salt random number using SHA1PNRG algorithm

    • Chandra Dev February 19, 2015 / 7:44 am

      I have already used in this artical. Please go through this.

  94. SHWET March 16, 2015 / 12:45 pm

    i am getting an error at this line of VerifyHash 😦
    byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

  95. Pratik May 3, 2015 / 6:36 am

    Hi Chandra,

    I was really looking for the encryption deception code to use in my website. could you please send me the source of this. It will be really very helpful.
    thanks.

  96. hemanth May 18, 2015 / 1:28 pm

    hi…sir may i know how to encrypt a particular column data from mdb file plss.

  97. gouri May 31, 2015 / 5:26 am

    sir please I need code for decryption..

  98. Ankita Dey September 24, 2015 / 4:14 am

    Please Sir Send me the code for visual studio 2010 in my mail id.Plzzzz….It’s urgent

  99. rajiv October 4, 2016 / 12:38 pm

    Hello Sir,
    Invalid length for a Base-64 char array or string.
    byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

    Please suggest me ASAP. It’s urgent.

    • rajiv October 5, 2016 / 11:49 am

      After increase size of password column from database my issue solved

      • Chandra Dev October 8, 2016 / 5:58 pm

        Good to know that you fixed the issue by yourself.

  100. Julianne October 9, 2016 / 2:51 am

    Great goods from you, man. I’ve understand your stuff previous to and
    you’re just too magnificent. I actually like what you’ve acquired
    here, really like what you are saying and the way in which you say it.
    You make it enjoyable and you still care for to keep
    it sensible. I cant wait to read far more from you.
    This is actually a wonderful site.

  101. Smithf761 October 11, 2016 / 10:53 pm

    Howdy! Would you mind if I share your blog with my twitter group? Theres lots of people that I believe would really enjoy your content. Please let me know.

  102. Smithb715 October 11, 2016 / 10:55 pm

    Hey, thanks for the post.Really thank you! Really Cool.

  103. Johng409 October 11, 2016 / 10:55 pm

    Appreciate you sharing, great blog post.Thanks Again. Really Cool. ddddgdbagebb

  104. Smithd831 October 11, 2016 / 10:56 pm

    Really great info can be found on site.

  105. wangkun September 24, 2017 / 8:43 am

    Thank you,it’s very useful and it saves me a lot of time,but can i ask you a question about when i transmit the user information to my database there are always two information about the same person?

  106. Christian May 3, 2018 / 9:07 am

    Hi sir,
    hope you’ll help me.
    First of all thank you for the amazing tutorial, very helpful.
    Now, my question. Why at this point of code in Helper.cs i have an hashValue with a lot of white space at the end?
    // Convert base64-encoded hash value into a byte array.
    byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

    Cause of this VerifyHash return me false and I can’t login succesfully.
    Thank you.

  107. JaIM May 18, 2018 / 7:23 pm

    Hello,
    Noob here, was researching on the encrypt/decrypt methods and not use whats provided with ASP.net. Ran into this article and is exactly what i was looking for. Is there a way i can get the complete code? There do not seem a link as mentioned at the bottom of the article “You can download the code from here”. Appreciate your assist.

  108. Derrick Agyemang February 21, 2019 / 4:10 pm

    Hello sir, tried to use your code. Had problems though when using the VerifyHash, and your skydrive doesnt seem to be active. Can you share the code to help solve this issue->> Invalid length for a Base-64 char array or string. Its quite urgent. Thanks

    • Derrick Agyemang February 21, 2019 / 5:19 pm

      I figured it out, thanks all the same for the post. Apparently the column saving the hash was small hence it truncated the values.

  109. Rahul Dhande November 22, 2019 / 10:11 am

    Dear Sir,
    I use the above code. It works perfectly for me.
    Now I want to decrypt this password as per requirement. and send the password in Mobile on forget password
    How I can do it as m not able to find decrypt function in code also shared attachment is not available.
    please send me the code on rahuldhande21@gmail.com

    • Chandradev November 24, 2019 / 10:28 am

      Hi Rahul, In this approach we don’t decrypt the password. You can give option to user to change the password. Have you seen any time get old password on gmail/facebook/homail ? They will give option to change the password.

  110. sreeharireddy December 9, 2019 / 10:08 am

    Hi Chandra,
    I am facing issue with code. Can u please send full code.

    Thanks.

    • Chandradev December 11, 2019 / 4:40 pm

      I have updated the source code download. Please download from there.

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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.