sha256.TransformBlock 在 Win10 通用应用中

sha256.TransformBlock in Win10 Universal App

我在 .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....}

我正在尝试在通用 Windows 10 应用程序中复制它。 但是,我无法在新的 .NET 库中的 SHA256 对象上找到 TransformBlock / TransformFinalBlock 函数。 我已经添加了对版本 4.0.0-beta-23409 of System.Security.Cryptography.Algorithms 的依赖。我得到的错误是:

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?)

如何获得与 .NET 4.5 相同的结果?

解决方案在另一个 class,IncrementalHash 中找到。 显然,Microsoft 想要将 HashAlgorithm 的有状态(TransformBlock 和 TransformFinalBlock)和 "stateless" (ComputeHash) 部分分开,因为它们没有很好的隔离。

无论如何,这是在通用 Windows 10 应用程序中复制代码的方法:

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();
}