Study/C#

파일의 무결성 확인 방법

13.d_dk 2022. 5. 5. 22:37
728x90
반응형

파일이 잘 기록되었는지 확인해야 할 필요가 있지 않을까?

  • 어떤 파일을 생성하고, 내용을 써넣을(write) 때가 있음
  • 이때 파일에 써넣는 중 문제가 생기면, 다시 이 파일을 읽어야 할 때 문제가 생길 수 있음
  • 예를 들면 1에서 10까지 파일에 써넣는데 8까지만 써넣어지고 9와 10은 작성되지 않거나 이상한 내용이 작성되는 경우가 있을 수 있음

 

방법 : 기록한 내용에 대한 '확인 해시값' 만들고 비교 하기

  • 이를 대비하여 작성할 파일 내용이 정상인지 확인하는 어떤 문자열을 만들어 같이 작성할 수 있음
  • 먼저 작성할 문자열(위의 경우 '1, 2, 3, ... 9, 10')을 통째로 해시값으로 바꿈
  • 이후 이 해시값을 먼저 파일에 써넣고 나머지 문자열을 써넣음
  • 이후 나머지 문자열을 해시값으로 바꾼 것과 이전에 기록해둔 해시값을 비교하여, 무결성 검사를 수행할 수 있음
  • 해시값을 바꾸는 함수로 C#에서 제공하는 MD5를 사용할 수 있음
  • MD5는 128비트의 암호화 해시 함수이며 주로 프로그램 및 파일이 원본 그대로인지 확인할 때 사용함(무결성 검사)

CheckHash를 통한 string 데이터 무결성 확인의 도식

 

예시 소스 코드와 설명

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CheckHashStr
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "checkHashTestText.txt";
 
            // write file with checkHash
            _writeFileWithCheckHash(filePath);
 
            // checkHash
            bool isCorrect = _checkHash(filePath);
 
            if (isCorrect)
            {
                Console.WriteLine("file is good");
            }
            else
            {
                Console.WriteLine("file txt have issue; not correct checkHash");
            }
 
            return;
        }
 
        static void _writeFileWithCheckHash(string filePath)
        {
            // str data
            string strData = "doDotLog is good!\nYes!";
 
            // make checkHash
            string checkHashStr = "";
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                checkHashStr = BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strData))).Replace("-"String.Empty);
                strData = checkHashStr + '\n' + strData;
            }
 
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath))
            {
                writer.WriteLine(strData);
                writer.Close();
            }
        }
 
        static bool _checkHash(string filePath)
        {
            // read file
            string[] readRawLines = System.IO.File.ReadAllLines(filePath);
            string[] readLines = new string[readRawLines.Length - 1];
 
            // check hash
            string checkHashStrAns = readRawLines[0];
            Array.Copy(readRawLines, 1, readLines, 0, readRawLines.Length - 1);
            string stmRcvDataStr = string.Join("\n", readLines);
            string checkHashStr = "";
 
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                checkHashStr = BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stmRcvDataStr))).Replace("-"String.Empty);
            }
 
            if (checkHashStr != checkHashStrAns)
            {
                return false;
            }
 
            return true;
        }
    }
}
 
 
cs
  • 이 소스코드에서 _writeFileWithCheckHash(filePath)를 실행하면 'checkHashTestText.txt'파일이 생성됨
  • 이 파일은 첫줄에 checkHash가 저장되어 있으며, 이 checkHash는 나머지 줄의 string을 바탕으로 생성된 것
  • _writeFileWithCheckHash(filePath) 함수는 저장된 파일을 읽어 첫 번째 줄의 checkHash와 나머지 string 데이터에 대하여 hash 값 비교를 수행
  • 첫 줄의 checkHash(A)를 제외한 나머지 string 데이터를 사용하여 checkHash(B)를 생성
  • 만약 이 checkHash 값인 (A)와 (B)가 같다면, 문제없이 파일을 생성하고 기록하였음을 확인할 수 있음
  • 만약 이 값들이 같지 않다면 파일을 생성하여 기록할 때 문제가 발생하였다고 간주할 수 있음
  • 파일을 기록하고, 기록한 파일을 다시 읽어서 어떤 일을 할 때 파일의 문제 여부를 확인할 수 있는 방법임 (파일의 무결성 확인)
  • 이러한 예시로는 복원 파일 생성 및 읽기가 있음 

 

Reference

 

Calculate a checksum for a string

I got a string of an arbitrary length (lets say 5 to 2000 characters) which I would like to calculate a checksum for. Requirements The same checksum must be returned each time a calculation is do...

stackoverflow.com

 

GitHub - daegukdo/TIL: today I learned

today I learned. Contribute to daegukdo/TIL development by creating an account on GitHub.

github.com

 

반응형