Jacob
Jacob

Reputation: 545

All hash values are identical using Microsoft SHA256

Using the following code I always get the same hash regardless of the input. Any ideas why that might be?

    private static SHA256 sha256;
    internal static byte[] HashForCDCR(this string value)
    {
        byte[] hash;
        using (var myStream = new System.IO.MemoryStream())
        {
            using (var sw = new System.IO.StreamWriter(myStream))
            {
                sw.Write(value);
                hash = sha256.ComputeHash(myStream);
            }
        }

        return hash;
    }

Upvotes: 1

Views: 1382

Answers (3)

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

You are computing hash of empty portion of the stream (the one immediately after content you wrote with sw.Write) so it always the same.

Cheap fix: sw.Flush();myStream.Position = 0;. Better fix is to finish writing and create new read only stream for encryption based on original stream:

using (var myStream = new System.IO.MemoryStream())
{
    using (var sw = new System.IO.StreamWriter(myStream))
    {
        sw.Write(value);
    }
    using (var readonlyStream = new MemoryStream(myStream.ToArray(), writable:false)
    {
       hash = sha256.ComputeHash(readonlyStream);
    }
}

Upvotes: 4

Jacob
Jacob

Reputation: 545

I will probably use the solution that Alexei Levenkov called a "cheap fix". However, I did come across one other way to make it work, which I will post for future readers:

var encoding = new System.Text.UTF8Encoding();
var bytes = encoding.GetBytes(value);
var hash = sha256.ComputeHash(bytes);
return hash;

Jacob

Upvotes: 0

nhrobin
nhrobin

Reputation: 903

You may need to flush your stream. For optimal performance StreamWriter doesn't write to stream immediately . It waits for its internal buffer to fill. Flushing the writer immediately flush the content of the internal buffer to underline stream.

     sw.Write(value);
     sw.Flush();
     myStream.Position = 0;
     hash = sha256.ComputeHash(myStream);

Upvotes: 1

Related Questions