1
votes

I have this working code in .NET 4.5:

var sha256 = System.Security.Cryptography.SHA256.Create();
var message = new byte[] {1, 2, 3};
var s = new byte[32];
var m = sha256.ComputeHash(message);
sha256.TransformBlock(m, 0, m.Length, m, 0);
sha256.TransformFinalBlock(s, 0, s.Length);
var x = sha256.Hash;  // x = {236, 196, 174, 128, 243....}

And I'm trying to replicate it in an universal Windows 10 App. However I cannot find TransformBlock / TransformFinalBlock functions on the SHA256-object in the new .NET libraries. I've added a dependency to version 4.0.0-beta-23409 of System.Security.Cryptography.Algorithms. And the errors I'm getting are:

error CS1061: 'SHA256' does not contain a definition for 'TransformBlock' and no extension method 'TransformBlock' accepting a first argument of type 'SHA256' could be found (are you missing a using directive or an assembly reference?)

error CS1061: 'SHA256' does not contain a definition for 'TransformFinalBlock' and no extension method 'TransformFinalBlock' accepting a first argument of type 'SHA256' could be found (are you missing a using directive or an assembly reference?)

error CS1061: 'SHA256' does not contain a definition for 'Hash' and no extension method 'Hash' accepting a first argument of type 'SHA256' could be found (are you missing a using directive or an assembly reference?)

How do I achieve the same result as in .NET 4.5?

1
Why do you call both ComputeHash and TransformBlock?Scott Chamberlain
@ScottChamberlain That's a really great question. I know very little about encryption. I ported the code from Java, and basically took line by line what they did in the original code.Stenkross

1 Answers

0
votes

The solution was found in another class, IncrementalHash. Apparently, Microsoft wanted to separate the stateful (TransformBlock and TransformFinalBlock) and "stateless" (ComputeHash) parts of HashAlgorithm, because they didn't have good isolation.

Anyway, here's how to replicate the code in a Universal Windows 10 App:

var message = new byte[] { 1, 2, 3 };
var s = new byte[32];
byte[] m;
byte[] x;

using (HashAlgorithm sha256 = SHA256.Create())
{
    m = sha256.ComputeHash(message);
}

using (IncrementalHash sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))
{
    sha256.AppendData(m);
    sha256.AppendData(s);
    x = sha256.GetHashAndReset();
}