StudentRik
StudentRik

Reputation: 1049

SHA256 adds \n into value

I have a couple of methods to do a little encryption and it always adds a \n in the value I am comparing.

Would this be due to some new line character thingy?

public static class Security
{
    public static string CreateHash(this string unHashed)
    {
        SHA256CryptoServiceProvider x = new SHA256CryptoServiceProvider();
        byte[] data = Encoding.UTF8.GetBytes(unHashed);
        data = x.ComputeHash(data);
        return Encoding.UTF8.GetString(data);
    }

    public static bool MatchHash(this string hashData, string hashUser)
    {
        if (hashUser == hashData)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

I am entering the value into one text box and running the CreateHash() to enter the value into another textbox (all for testing). I then run my comparison check from another text box.

protected void btn_dehash_Click(object sender, EventArgs e)
{
// get value entered and hash it
var matchPass = txt_password.Text.CreateHash();

// populate lbl with true or false
lbl_Name.Text = txt_hashed.Text.MatchHash(matchPass) ? "true" : "false";
}

The results I get from MD5 are ok and work as this is much shorter. I want to use a more secure method so I have used SHA256 and this is the results I get from the comparison.

SHA256 Results

Does anybody know why this is happening?

Upvotes: 0

Views: 227

Answers (1)

Jeff Foster
Jeff Foster

Reputation: 44736

Don't turn the hash into a string! Keep it as a byte array.

The hash represents a sequence of bytes that may or may not be valid as UTF-8.

If you want a readable hash then do something similar to:

    byte[] hash = x.ComputeHash(bytes);
    string hashString = string.Empty;
    foreach (byte x in hash)
    {
        // Turn each byte into it's hex equivalent (00 to FF).
        hashString += String.Format("{0:x2}", x);
    }
    return hashString;

Or, as the comments suggest, use base 64 encoding.

Upvotes: 5

Related Questions