Click here to Skip to main content
14,454,989 members
Rate this:
Please Sign up or sign in to vote.
See more:
hi, i want to do login using username and password. i want to decrypt the password in database to match with the password key in. if the password key in is same with password database, it will log in to the system. but my decrypt function did not return the exact password like key in password. for example, my database password is 'gZ+c6cHMVSz+HwCjIZOLpw==' which is 1234 and my key in password is '1234'. i run the application then try to key in username and password '1234' but decrypt function return me '찚\ufae2懸⋕Ṻ竛腄'. can you help me or correct me which im wrong.

What I have tried:

this is what i have done:

protected void Unnamed_Click(object sender, EventArgs e)
        {            
            using (MySqlConnection con = new MySqlConnection(connStr))
            {                
                using (MySqlCommand cmd = new MySqlCommand("SELECT user_id, username, password FROM users WHERE username = @username"))
                {
                    cmd.Parameters.AddWithValue("@username", txtUsername.Text.Trim());
                    cmd.Connection = con;

                    string pwd1 = txtPassword.Text;

                    MySqlDataReader dr;
                    con.Open();
                    dr = cmd.ExecuteReader();

                    if (dr.Read())
                    {
                        string id = dr["user_id"].ToString();
                        string dbUsername = dr["username"].ToString();
                        string dbPwd = dr["password"].ToString();

                        string pwd = Decrypt(dbPwd);
                        
                        if (pwd == pwd1)
                        {
                            Response.Redirect("~/dashboard.aspx");
                        }
                        else
                        {
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Invalid Username and Password.');", true);
                            Response.Redirect("login.aspx");
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Invalid Username and Password.');", true);
                        Response.Redirect("login.aspx");
                    }
                    con.Close();
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            Response.Redirect(Request.Url.AbsoluteUri);
        }


private string Decrypt(string cipherText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Mode = CipherMode.CBC;
                encryptor.Padding = PaddingMode.Zeros;
                encryptor.FeedbackSize = 128;
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV = pdb.GetBytes(16);

                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(cipherBytes, 0, cipherBytes.Length);
                        cs.Close();
                    }
                    cipherText = Encoding.Unicode.GetString(ms.ToArray());
                }
            }
            return cipherText;
        }


Updated question:

this is the way how i compare the hashes but it says 'Invalid salt'.

using (MySqlConnection con = new MySqlConnection(connStr))
            {                
                using (MySqlCommand cmd = new MySqlCommand("SELECT user_id, username, password FROM users WHERE username = @username"))
                {
                    cmd.Parameters.AddWithValue("@username", txtUsername.Text.Trim());
                    cmd.Connection = con;

                    string pwd1 = txtPassword.Text;

                    MySqlDataReader dr;
                    con.Open();
                    dr = cmd.ExecuteReader();

                    if (dr.Read())
                    {
                        string id = dr["user_id"].ToString();
                        string dbUsername = dr["username"].ToString();
                        string dbPwd = dr["password"].ToString();

                        //string pwd = Decrypt(dbPwd);
                        
                        bool result = verifyPassword(dbPwd, pwd1);

                        if (result) //if the verifyPassword is true
                        {                            
                            Response.Redirect("~/dashboard.aspx");
                        }
                        else
                        {
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Invalid Username and Password.');", true);
                            Response.Redirect("login.aspx");
                        }
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Invalid Username and Password.');", true);
                        Response.Redirect("login.aspx");
                    }
                    con.Close();
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();


private bool verifyPassword(string dbPwd, string pwd1)
        {
            bool result = false;
            byte[] data = Encoding.Unicode.GetBytes(pwd1);

            string salt = dbPwd.Substring(0, 24);
            string hash_pwd = Crypter.Blowfish.Crypt(data, salt);

            if (dbPwd == hash_pwd)
            {
                result = true;
            }
            return result;
        }
Posted
Updated 1-Aug-18 21:58pm
v3
Comments
F-ES Sitecore 18-Sep-17 4:58am
   
You should google for articles about password hashing to understand the concept first, as until you understand the concept you're not going to be able to get it working.

Each user should have a hashed password and a salt stored, and what you need to do is use the hashing code (Crypter.Blowfish.Crypt) using the password the user typed in and the salt you read from the database for that user, and compare the result with the stored password for that user.
Elaine94 18-Sep-17 5:03am
   
is it like this?
private bool verifyPassword(string dbPwd, string pwd1)
{
bool result = false;

string salt = dbPwd.Substring(0, 24);
string hash_pwd = Crypter.Blowfish.Crypt(pwd1, salt); //error here

if (dbPwd == hash_pwd)
{
result = true;
}
return result;
}

i found this in google but when i try, the pwd1 has error 'cannot convert from byte[] to string'.
F-ES Sitecore 18-Sep-17 5:21am
   
"salt" is going to be a string you've got from somewhere, as I said usually it is stored with the user record, so as well as getting the username and password for that user you'll get the salt too. Your code is treating the stored password as the salt.

The problem is we don't know how you are storing the password in the first place so we can't give exact help. How you verify the password depends on how you store the password and you haven't explained how that works, if we don't know how you store the password we can't tell you how to verify it.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

The answer is you can't, it's a calculated hash and is not reversible. Read the answers to the same question asked here: Decryption of Encrypted Password[^]
   
Comments
Elaine94 18-Sep-17 1:47am
   
so i need to compare the hashes?
Graeme_Grant 18-Sep-17 1:49am
   
That would be a yes.
Elaine94 18-Sep-17 1:57am
   
can u take a look my updated question, please.
Graeme_Grant 18-Sep-17 2:13am
   
You need to use the same code/function in your compare method that was used to created the encrypted password in the first place.
Elaine94 18-Sep-17 2:17am
   
im sorry. i do not understand. can u explain me more.
Graeme_Grant 18-Sep-17 2:18am
   
How did you create the encrypted password?
Elaine94 18-Sep-17 2:20am
   
i create the encrypted password like this:

[code removed]

but the encrypted password is not the same as in database.
Graeme_Grant 18-Sep-17 2:22am
   
That was my question: how was the password in the database created? You need to use the same encoding keys... For example: My car key will not unlock your car door.
Elaine94 18-Sep-17 3:05am
   
ok. i try first

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100