8

I am currently working on a visual studio C# windows form project. However, I am confused by how SHA256 + salted works. I found some examples online but unable to understand how can I call this function.

I would like to call this function in a login form connecting to a database (Microsoft Access 2010).

  • How do I call this function by a click of a button and reading the password from a Textbox?
  • How do i display out the hash value in a Messagebox.Show method? (For my testing purpose)
  • Is it possible to compare two text (hashed and salted) and giving a positive result?

    public static string sha256encrypt(string phrase, string UserName)
    {
        string salt = CreateSalt(UserName);
        string saltAndPwd = String.Concat(phrase, salt);
        UTF8Encoding encoder = new UTF8Encoding();
        SHA256Managed sha256hasher = new SHA256Managed();
        byte[] hashedDataBytes =      sha256hasher.ComputeHash(encoder.GetBytes(saltAndPwd));
        string hashedPwd = String.Concat(byteArrayToString(hashedDataBytes), salt);
        return hashedPwd;
    }
    
    public static string byteArrayToString(byte[] inputArray)
    {
        StringBuilder output = new StringBuilder("");
        for (int i = 0; i < inputArray.Length; i++)
        {
            output.Append(inputArray[i].ToString("X2"));
        }
        return output.ToString();
    }
    
    private static string CreateSalt(string UserName)
    {
        string username = UserName;
        byte[] userBytes; 
        string salt;
        userBytes = ASCIIEncoding.ASCII.GetBytes(username);
        long XORED = 0x00; 
    
        foreach (int x in userBytes)
            XORED = XORED ^ x;
    
        Random rand = new Random(Convert.ToInt32(XORED));
        salt = rand.Next().ToString();
        salt += rand.Next().ToString();
        salt += rand.Next().ToString();
        salt += rand.Next().ToString();
        return salt;
    }
    

How do I create an SHA256 hash with salt?

shavalue = (sha256encrypt("password", "username");
saltedandhashtext = CreateSalt(shavalue);
Dave Hillier
  • 18,105
  • 9
  • 43
  • 87
David
  • 97
  • 1
  • 1
  • 4
  • 4
    I'm not sure if I'd trust this piece of code without reading *and understanding* it, as it calls SHA-256 "encryption" and only uses up to 256 different salt values... – Matti Virkkunen Jan 01 '13 at 17:17
  • 5
    I wouldn't waste any time on getting this code to work. Throw it out, and start with new code. In particular use `Rfc2898DeriveBytes` which uses a stretched hashfunction and can create a salt by itself. – CodesInChaos Jan 01 '13 at 17:44
  • 2
    Since you are hashing passwords, you should consider to use a slow key-derivation function like PBKDF2, in CSharp it can be implemented with the [Rfc2898DeriveBytes](http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes%28v=vs.100%29) class, as CodesInChaos already mentioned. – martinstoeckli Jan 01 '13 at 17:46
  • @CodesInChaos ... Please take note for .Net 7 : SYSLIB0041: Some Rfc2898DeriveBytes constructors are obsolete. Refer to https://learn.microsoft.com/en-us/dotnet/fundamentals/syslib-diagnostics/syslib0041 I found this out just TODAY 11Apr2023. – John D Apr 11 '23 at 20:55

3 Answers3

4

What you would do is, on the click of the button, pass the textbox value and username to the sha256encrypt function, for example:

    private void button1_Click(object sender, EventArgs e)
    {
        sha256encrypt(textBox1.Text, "SampleUserName");
    }

For the second question, do the same but with Messagebox.Show:

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(sha256encrypt(textBox1.Text, "SampleUserName"));
    }

Third point: I am not sure exactly what you mean, but if you want to Salt a text and compare it with the Hashed text:

if(sha256encrypt("password", "username") == CreateSalt("password"))
   return true;
else
   return false;

Or if you want to compare them manually:

MessageBox.Show(sha256encrypt("password", "username") + "\n\r" + CreateSalt("password"));
CC Inc
  • 5,842
  • 3
  • 33
  • 64
2

For the first question look at CC Inc's answer.

To the second point: MessageBox.Show(sha256encrypt(textBox1.Text, "SampleUserName"));

3) Yes, it is.

You can compare two strings with the == comparator or string.Equals().

public bool compareHashs(string hash1, string hash2){
   if(hash1.Equals(hash2) //or hash1 == hash2
      return true;
   }else{
      return false;
   }  
}
jAC
  • 5,195
  • 6
  • 40
  • 55
0
public string ComputeSHA256Hash(string rawData)
{
    // Create a SHA256   
    using (SHA256 sha256Hash = SHA256.Create())
    {
        // ComputeHash - returns byte array  
        byte[] bytes = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
        // Convert byte array to a string   
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            builder.Append(bytes[i].ToString("x2"));
        }
        return builder.ToString();
    }
}
  • This appears to be the correct way to do it now. Sha256Managed has been deprecated, SHA256.Create() is now the method they are saying to use. – Zonus Nov 22 '22 at 20:39