-2

I have an ASP.NET web project with web form. for my log in, I need to store user password in hashed format. And also retrieve the password when logging in.

My table has columns

username varchar(50) Primary key, 
mobile varchar(50),
pass varchar(50)

My C# code is

try
{
   Console.WriteLine("inside try");
   SqlConnection con = new SqlConnection(strcon);
   con.Open();
   SqlCommand cmd = new SqlCommand("INSERT INTO signinup ([username], [mobile], [pass]) 
                                    VALUES (@username, @mobile, @pass)", con);

   cmd.Parameters.AddWithValue("@username", usernametextbox.Text.Trim());
   cmd.Parameters.AddWithValue("@mobile", mobiletextbox.Text.Trim());
   cmd.Parameters.AddWithValue("@pass", passwordtextbox.Text.Trim());

   cmd.ExecuteNonQuery();
   con.Close();

   Response.Redirect("~/login.aspx");
} 
catch (Exception ex)
{
   Response.Write("<script>alert('Error: " + ex.Message + "');</script>");
}

I tried this

string plainPassword = passwordtextbox.Text.Trim();
byte[] hashedPasswordBytes;

using (SHA256 sha256 = SHA256.Create())
{
  hashedPasswordBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainPassword));
}
             
string hashedPassword = BitConverter.ToString(hashedPasswordBytes).Replace("-", string.Empty);
cmd.Parameters.AddWithValue("@pass", hashedPassword );

And also this

string password = passwordtextbox.Text.Trim();
string hashedPassword = HashPassword(password);

cmd.Parameters.AddWithValue("@pass", hashedPassword);

private string HashPassword(string password)
{
  using (SHA256 sha256 = SHA256.Create())
  {
    byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
    byte[] hashBytes = sha256.ComputeHash(passwordBytes);
    string hashedPassword = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    return hashedPassword;
   }
}

But it's not working

TylerH
  • 20,799
  • 66
  • 75
  • 101
  • 2
    Do you know that all these issues are already solved by the [Microsoft ASP.NET Identity](https://www.codeproject.com/Articles/762428/ASP-NET-MVC-and-Identity-Understanding-the-Basics) libraries? – Steve Jun 17 '23 at 08:54
  • 2
    Thanks to rainbow tables hashed passwords are not really any better than plaintext passwords. If you must use password authentication at least look into salt-and-hashing techniques, where each user's password gets hashed with their own unique salt value. – AlwaysLearning Jun 17 '23 at 09:10
  • 1
    Also, you should specify correct data types and length/precision/scale when adding parameters to SqlCommands. [Can we stop using AddWithValue() already?](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) ...and... [AddWithValue is Evil.](https://www.dbdelta.com/addwithvalue-is-evil/) – AlwaysLearning Jun 17 '23 at 09:12
  • 2
    You need to provide a better explanation of your problem than "But it's not working". At what point are the expected results different from your actual results, and what are your expected and actual results at that point. If you are getting an error, what is the exact error message. – T N Jun 17 '23 at 14:06
  • Leading spaces in passwords can be significant. Don't trim them. Also, what do you mean by "Not working"? How is it failing for you? Finally, you should look into using the BCrypt package on Nuget, which makes some of this easier and stronger. – Joel Coehoorn Jun 19 '23 at 14:17

1 Answers1

0

This is what I use on basic projects for myself an a small group, it is something? Just need to pass in an encryption key which you can get generated online.

public string? EncryptString(string key, string plainText)
{
    try
    {
        byte[] iv = new byte[16];
        byte[] array;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = iv;
            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                    {
                        streamWriter.Write(plainText);
                    }
                    array = memoryStream.ToArray();
                }
            }
        }

        return Convert.ToBase64String(array);
    }
    catch (Exception ex) 
    {
        return null;
    }
}

public string? DecryptString(string key, string cipherText)
{
    try
    {
        byte[] iv = new byte[16];
        byte[] buffer = Convert.FromBase64String(cipherText);

        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = iv;
            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            using (MemoryStream memoryStream = new MemoryStream(buffer))
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
                    {
                        return streamReader.ReadToEnd();
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        return null;
    }
}
alexg1380
  • 23
  • 2