2017-10-19 4 views
2

.NET API를 배우려고하고 있는데 원본 파일의 키와 XML 파일의 키를 비교하는 프로그램을 만들었습니다. 성공하지 못했습니다. (C# .NET HMACSHA256 클래스)

나는 다음과 같은 exaple (문서를 varifying에 대한 세 번째 방법을 사용 :

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

지금 내 프로그램이 실행하지만, 항상 파일이 내가 그 절대적으로 확신에도 불구하고 위조 된 것을 말한다 그들은 그냥 그들을 만든되지 않기 때문에 여기에

내 코드입니다.

VerifyDocument.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); 
    } 
} 
} 

} 

어떤 도움을 크게 감상 할 수있다!

+0

"내가 뭘 잘못하고 있니?" 진짜 질문이 아닙니다. [ask]를 읽고 질문을 편집하여 적절한 제목을 지정하십시오. –

+0

확인할 파일을 어떻게 작성했는지 공유해야합니다. 확인한 파일이 코드의 예상대로 (파일의 시작 부분이 나머지 파일의 HMAC-SHA256) 포맷되어 있다고 가정하면 공유 한 코드가 적당합니다. – smarx

+0

안녕하세요. XML 키를 생성하고 지정된 파일 의 내용에 대해 HMAC를 계산하는 것을 포함하여 사용중인 3 개의 작은 프로그램을 공유했습니다. –

답변

0

"기호"프로그램은 inStream을 읽고 HMAC 만 outStream에 기록합니다.

"확인"프로그램은 파일을 읽고 HMAC 다음에 데이터가 올 것으로 예상합니다.

"기호"는 inStream을 되감기 한 다음 outStream으로 복사하거나 두 파일을 독립적으로 보려면 "확인"을 변경해야합니다.

0

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); 
관련 문제