프로그래밍/C#

[C#] 비밀번호(패스워드) 암호화 SHA256알고리즘

ss-pro 2020. 10. 3. 22:26
반응형

비밀번호 암호화를 해야될경우에 Sha256 단방향 알고리즘을 많이 사용합니다. 문자열을 입력받아서 SHA256알고리즘적용하여 암호화 처리를 해보도록 하겠습니다. SHA256 Class를 사용해서 처리하면되고 해당 클래스를 사용하기 위해서는 System.Security.Cryptography네임스페이스를 추가해야합니다. 

1
using System.Security.Cryptography;

아래와 같은순서로 변환처리가 됩니다. 
1. 입력받은 문자열을  바이트배열로 변환 
2. 바이트배열을 암호화된 32byte 해쉬값으로 생성

1
2
3
4
using (SHA256 mySHA256 = SHA256.Create())
{
    hashValue = mySHA256.ComputeHash(array);
}

3. 32byte 해쉬값을 16진수로 변환하여 64자리로 만들어줌. 결과값을 항상 64자리 문자열값이 나옵니다. 

1
2
3
4
5
//32byte 해쉬값을 16진수로변환하여 64자리로 만듬
for (int i = 0; i < hashValue.Length; i++)
{
    result += hashValue[i].ToString("x2");
}

전체소소코드

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
 
namespace Sha265
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("패스워드를 입력해주세요..");
            string password = Console.ReadLine();
            string result =  EncryptionHelper.EncryptionSHA256(password);
            Console.WriteLine("SHA암호화 결과값:{0}", result);
        }
    }
 
    public class EncryptionHelper
    {
        public static string EncryptionSHA256(string message)
        {
            //입력받은 문자열을 바이트배열로 변환
            byte[] array = Encoding.Default.GetBytes(message);
            byte[] hashValue;
            string result  = string.Empty;
            
            //바이트배열을 암호화된 32byte 해쉬값으로 생성
            using (SHA256 mySHA256 = SHA256.Create())
            {
                hashValue = mySHA256.ComputeHash(array);
            }
            //32byte 해쉬값을 16진수로변환하여 64자리로 만듬
            for (int i = 0; i < hashValue.Length; i++)
            {
                result += hashValue[i].ToString("x2");
            }
            return result;
        }
    }
}

참고)
docs.microsoft.com/ko-kr/dotnet/api/system.security.cryptography.sha256?view=netcore-3.1

반응형