Morgan Keilty
Morgan Keilty

Reputation: 53

How to incorporate this decryption into my code, to translate hashed password back to original

I am creating a website which has a SQL database connected to a sign up and log in function in the website. I want to hash the password before it is sent off to the database, which I have done successfully, however I am finding it very difficult to decrypt the hashed password back when the user is attempting to log in.

here is my user log in page, where i want to incorporate the following code...

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

namespace DogWalkingSite
{
    public partial class userlogin : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection con = new SqlConnection(strcon);
                //checking to see if the connection is closed
                if (con.State == System.Data.ConnectionState.Closed)
                {
                    //opens state to connect to database
                    con.Open();
                }

                SqlCommand cmd = new SqlCommand("select * from user_master_tbl where user_id= '"+TextBox1.Text.Trim()+ "' and password= '" + TextBox2.Text.Trim() + "'", con);
                SqlDataReader dr = cmd.ExecuteReader();
                //HasRows will become false if the inputs are false
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        Response.Write("<script>" + "alert('"+dr.GetValue(5).ToString()+"');" + "</script>");
                        //sessions used to determine when to show buttons
                        Session["username"] = dr.GetValue(5).ToString();
                        Session["name"] = dr.GetValue(0).ToString();
                        Session["role"] = "user";
                    }

                    Response.Redirect("homepage.aspx");
                }
                else
                {
                    Response.Write("<script>" + "alert('Username does not exist');" + "</script>");
                }

            }
            catch (Exception ex)
            {

            }
        }
    }
} ```




``` public static bool VerifyPassword(string username,

                    string password,AccountDataContext context)

    {

        var user = context.UserAccounts.FirstOrDefault(p => p.UserName == username);

        if (user != null)

        {

            string salt = user.Password.Substring(user.Password.Length - DefaultSaltSize);

            string hashedPassword = CreateHash(password, salt);

            return hashedPassword.Equals(user.Password);

        }

        return false;



    } ```


Upvotes: 1

Views: 176

Answers (3)

rfmodulator
rfmodulator

Reputation: 3738

Your original question has been answered, but I want to help you out.

This is too much for a comment, so I'll just post it here...

Instead of:

SqlCommand cmd = new SqlCommand("select * from user_master_tbl where user_id= '"+TextBox1.Text.Trim()+ "' and password= '" + TextBox2.Text.Trim() + "'", con);

Do this:

SqlCommand cmd = new SqlCommand("select * from user_master_tbl where user_id = '@user' and password = '@pass'", con);
cmd.Parameters.AddWithValue("@user", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("@pass", FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text.Trim(), "SHA1"));

Always parameterize user input like this. This will protect you from SQL injection attacks. Plus it's a little more readable, IMO.

Upvotes: 1

user12228709
user12228709

Reputation:

Just to throw in something that was recently taught to me, a true Password Hash, cannot be reversed.

That is the difference between Cryptography and Password Hashing.

While it would take some effort to break something encrypted, it could be done. A Password Hash is one way.

enter image description here

I have a Nuget package that handles both, here is a live sample:

DataJuggler.Core.Cryptography .Net Core

DataJuggler.Net.Cryptography .Net Framework

  // Create passwordHash, trying up to 3 times to ensure it can be verified
  passwordHash = CryptographyHelper.GeneratePasswordHash(password, keyCode, 3);

  // Verify Hash
  verified = CryptographyHelper.VerifyHash(password, keyCode, passwordHash);

So in your database store the password hash, and if hacked a value looks like:

6aerTg31w4wkD2EEKalHtuwzd6n2W8VnrhtN+tozftd+5ZIk2JXuylL0mZJpR1j1xrObfmbSGzaPeBY2lj+lmoUu4tWpYvrBsFIpvmwb/cw=

Live Demo:

https://blazorcrypto.datajuggler.com

Video including 3D animation to illustrate this point:

https://youtu.be/w4NrmpeHykE

Upvotes: 0

Sd9ToU
Sd9ToU

Reputation: 11

When user sign up the website, hashing the value and saves it to the DB, and compares each time user log in to the hashed value.

Decrypting a hash is impossible. Because the hash is a one-way function. But you can try crack using a Dictionary Attack. (Rainbow Table)

Hmm.. was it helpful-_-?

Upvotes: 1

Related Questions