【问题标题】:Unsuccessful verifying (C# .NET HMACSHA256 Class)验证失败(C# .NET HMACSHA256 类)
【发布时间】:2017-10-19 14:39:30
【问题描述】:

我正在尝试学习 .NET API,并创建了一个程序,将源文件中的密钥与 XML 文件中的密钥进行比较。

我使用了下面的例子(第三种验证文档的方法:

https://docs.microsoft.com/en-gb/dotnet/api/system.security.cryptography.hmacsha256?view=netframework-4.7.1

现在我的程序正在运行,但它总是说文件已被篡改,尽管我完全确定它们没有被篡改,因为我刚刚创建了它们。

这是我的代码:

验证文档.cs

using System;
using System.IO;
using System.Security.Cryptography;
using System.Xml.Serialization;

public class VerifyDocument
{

public static void Main(string[] args)
{

XmlSerializer xml = new XmlSerializer(typeof(byte[]));
byte[] key;
string keyFile = args[1];
string sourceFile = args[0];
using (StreamReader reader = new StreamReader(keyFile)) {
  key = (byte[]) xml.Deserialize(reader);
}

bool err = false;

        using (HMACSHA256 hmac = new HMACSHA256(key)) // Initialize the keyed hash object.
        {

            byte[] storedHash = new byte[hmac.HashSize / 8]; // Create an array to hold the keyed hash value read from the file.

            using (FileStream inStream = new FileStream(sourceFile, FileMode.Open)) // Create a FileStream for the source file.
            {

                inStream.Read(storedHash, 0, storedHash.Length); // Read in the storedHash.

                byte[] computedHash = hmac.ComputeHash(inStream);
                // compare the computed hash with the stored value

                for (int i = 0; i < storedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        err = true;
                    }
                }
            }
        }
        if (err)
        {
            Console.WriteLine("Hash values differ! Signed file has been tampered with!");

        }
        else
        {
            Console.WriteLine("Hash values agree -- no tampering occurred.");

        }

}

}

SignDocument.cs

using System;
using System.IO;
using System.Security.Cryptography;
using System.Xml.Serialization;

public class HMACSHA256example
{    

   public static void Main(string[] args)
  {


    if (args.Length != 2) {
      Console.WriteLine("Usage: [mono] SignDocument.exe <filename> <key>");
      Environment.Exit(1);
    } else
    {
      XmlSerializer xml = new XmlSerializer(typeof(byte[]));
      byte[] key;
      string keyFile = args[1];
      string sourceFile = args[0];
      string destFile = sourceFile + ".hash";
      using (StreamReader reader = new StreamReader(keyFile)) {
        key = (byte[]) xml.Deserialize(reader);
      }

      using (HMACSHA256 hmac = new HMACSHA256(key)) // Initialize the keyed hash object.
      {
          using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
          {
              using (FileStream outStream = new FileStream(destFile, FileMode.Create))
              {

                  byte[] hashValue = hmac.ComputeHash(inStream); // Compute the hash of the input file.


                  outStream.Write(hashValue, 0, hashValue.Length); // Write the computed hash value to the output file.

          }
      }

    }

 }
 }
 }

CreateKey.cs

using System;
using System.IO;
using System.Security.Cryptography;
using System.Xml.Serialization;

namespace COMP3911.Crypto {


class CreateKey {
static void Main(string[] args) {

  string input;

  if (args.Length == 0) {
    Console.WriteLine("Usage: [mono] CreateKey.exe <filename>");
    Environment.Exit(1);
  }

  byte[] secretkey = new Byte[64];
        //RNGCryptoServiceProvider is an implementation of a random number generator.
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            // The array is now filled with cryptographically strong random bytes.
            rng.GetBytes(secretkey);
        }


  // XML
  string keyfile = args[0] + ".key";
  using (StreamWriter output = new StreamWriter(keyfile, false)) {
    XmlSerializer xml = new XmlSerializer(typeof(byte[]));
    xml.Serialize(output, secretkey);
  }
}
}

}

任何帮助将不胜感激!

【问题讨论】:

  • “我做错了什么?”不是一个真正的问题。请阅读How to Ask 并编辑您的问题以获得正确的标题
  • 你需要分享你是如何创建你正在检查的文件的。您共享的代码看起来很合理,假设您正在检查的文件按照代码预期的方式格式化(文件的开头是文件其余部分的 HMAC-SHA256)。
  • 嗨 smarx。我刚刚分享了我正在使用的 3 个小程序,包括一个生成 XML 密钥并为指定文件的内容计算 HMAC 的程序。

标签: c# .net cryptography hmac hmacsha1


【解决方案1】:

您的“签名”程序读取 inStream 并将 HMAC 写入 outStream。

您的“验证”程序读取一个文件并期望它是 HMAC,后跟数据。

要么“签名”需要倒带inStream,然后将其复制到outStream,或者您需要更改“验证”以分别查看这两个文件。

【讨论】:

    【解决方案2】:

    SignDocument.cs 有错误。您正在编写签名,但未能写入文件的其余部分。

    应该是这样的(主要是从您链接到的文档页面复制的):

    using (HMACSHA256 hmac = new HMACSHA256(key)) // Initialize the keyed hash object.
    {
        using (FileStream inStream = new FileStream(sourceFile, FileMode.Open))
        {
            using (FileStream outStream = new FileStream(destFile, FileMode.Create))
            {
                byte[] hashValue = hmac.ComputeHash(inStream); // Compute the hash of the input file.
                outStream.Write(hashValue, 0, hashValue.Length); // Write the computed hash value to the output file.
    
                inStream.Position = 0;
                int bytesRead;
                byte[] buffer = new byte[1024];
                do
                {
                    bytesRead = inStream.Read(buffer, 0, 1024);
                    outStream.Write(buffer, 0, bytesRead);
                } while (bytesRead > 0);
    
            }
        }
    }
    

    更新

    不知道为什么 MSDN 版本不使用CopyTo,但似乎更好:

    byte[] hashValue = hmac.ComputeHash(inStream);
    outStream.Write(hashValue, 0, hashValue.Length);
    
    inStream.Position = 0;
    inStream.CopyTo(outStream);
    

    【讨论】:

      猜你喜欢
      • 2020-03-22
      • 2015-02-01
      • 2018-02-08
      • 2011-10-09
      • 2018-06-19
      • 2011-04-13
      • 2017-06-22
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多