Dev Language/C#

AES, SHA 암호화 3, C#

타카스 류지 2017. 3. 30. 11:34

닷넷.. C#을 통해 AES, SHA 암호화를 진행하겠습니다.

음.. visual studio 정품이 없어 고민하다가 검색해보니.. 언제부터 나왔는지 모르겠는데 https://www.visualstudio.com/ko-kr/visual-studio-homepage-vs.aspx에 가니 visual studio 커뮤니티라는 공짜가 있네요... 냉큼 설치하고 진행~

콘솔 응용 프로그램 프로젝트 생성하고 코드~

using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

 

namespace CryptoConsole

{

    class Program

    {

        static void Main(string[] args)

        {

            string str1 = "암호화되지 않은 문자";

            Console.WriteLine("plain : " + str1);

 

            string str2 = encryptAES128(str1);

            Console.WriteLine("AES128 encrypted : " + str2);

 

            string str3 = decryptAES128(str2);

            Console.WriteLine("AES128 decrypted : " + str3);

 

            string str4 = encryptAES256(str1);

            Console.WriteLine("AES256 encrypted : " + str4);

 

            string str5 = decryptAES256(str4);

            Console.WriteLine("AES256 decrypted : " + str5);

 

            string str6 = encryptSHA256(str1);

            Console.WriteLine("SHA256 encrypted : " + str6);

 

            Console.WriteLine("end");

 

        }

 

        // 

        private static readonly string KEY = "01234567890123456789012345678901";

 

        //128bit (16자리)

        private static readonly string KEY_128 = KEY.Substring(0, 128 / 8);

 

        //256bit (32자리)

        private static readonly string KEY_256 = KEY.Substring(0, 256 / 8);

        

        //AES 128 암호화.., CBC, PKCS7, 예외발생하면 null

        public static string encryptAES128(string plain)

        {

            try

            {

                //바이트로 변환

                byte[] plainBytes = Encoding.UTF8.GetBytes(plain);

 

                //레인달 알고리듬

                RijndaelManaged rm = new RijndaelManaged();

                //자바에서 사용한 운용모드와 패딩방법 일치시킴(AES/CBC/PKCS5Padding)

                rm.Mode = CipherMode.CBC;

                rm.Padding = PaddingMode.PKCS7;

                rm.KeySize = 128;

 

                //메모리스트림 생성

                MemoryStream memoryStream = new MemoryStream();

 

                //key, iv값 정의

                ICryptoTransform encryptor = rm.CreateEncryptor(Encoding.UTF8.GetBytes(KEY_128), Encoding.UTF8.GetBytes(KEY_128));

                //크립토스트림을 키와 IV값으로 메모리스트림을 이용하여 생성

                CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

 

                //크립트스트림에 바이트배열을 쓰고 플러시..

                cryptoStream.Write(plainBytes, 0, plainBytes.Length);

                cryptoStream.FlushFinalBlock();

 

                //메모리스트림에 담겨있는 암호화된 바이트배열을 담음

                byte[] encryptBytes = memoryStream.ToArray();

 

                //베이스64로 변환

                string encryptString = Convert.ToBase64String(encryptBytes);

 

                //스트림 닫기.

                cryptoStream.Close();

                memoryStream.Close();

 

                return encryptString;

            }

            catch (Exception)

            {

                return null;

            }

        }

 

        //AES128 복호화.., CBC, PKCS7, 예외발생하면 null

        public static string decryptAES128(string encrypt)

        {

            try

            {

                //base64를 바이트로 변환

                byte[] encryptBytes = Convert.FromBase64String(encrypt);

                //byte[] encryptBytes = Encoding.UTF8.GetBytes(encryptString);

 

                //레인달 알고리듬

                RijndaelManaged rm = new RijndaelManaged();

                //자바에서 사용한 운용모드와 패딩방법 일치시킴(AES/CBC/PKCS5Padding)

                rm.Mode = CipherMode.CBC;

                rm.Padding = PaddingMode.PKCS7;

                rm.KeySize = 128;

 

                //메모리스트림 생성

                MemoryStream memoryStream = new MemoryStream(encryptBytes);

 

                //key, iv값 정의

                ICryptoTransform decryptor = rm.CreateDecryptor(Encoding.UTF8.GetBytes(KEY_128), Encoding.UTF8.GetBytes(KEY_128));

                //크립토스트림을 키와 IV값으로 메모리스트림을 이용하여 생성

                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

 

                //복호화된 데이터를 담을 바이트 배열을 선언한다.

                byte[] plainBytes = new byte[encryptBytes.Length];

 

                int plainCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);

 

                //복호화된 바이트 배열을 string으로 변환

                string plainString = Encoding.UTF8.GetString(plainBytes, 0, plainCount);

 

                //스트림 닫기.

                cryptoStream.Close();

                memoryStream.Close();

 

                return plainString;

            }

            catch (Exception)

            {

                return null;

            }

        }

 

        //AES 256 암호화.., CBC, PKCS7, 예외발생하면 null

        public static string encryptAES256(string plain)

        {

            try

            {

                //바이트로 변환

                byte[] plainBytes = Encoding.UTF8.GetBytes(plain);

 

                //레인달 알고리듬

                RijndaelManaged rm = new RijndaelManaged();

                //자바에서 사용한 운용모드와 패딩방법 일치시킴(AES/CBC/PKCS5Padding)

                rm.Mode = CipherMode.CBC;

                rm.Padding = PaddingMode.PKCS7;

                rm.KeySize = 256;

    

                //메모리스트림 생성

                MemoryStream memoryStream = new MemoryStream();

 

                //key, iv값 정의

                ICryptoTransform encryptor = rm.CreateEncryptor(Encoding.UTF8.GetBytes(KEY_256), Encoding.UTF8.GetBytes(KEY_128));

                //크립토스트림을 키와 IV값으로 메모리스트림을 이용하여 생성

                CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);

 

                //크립트스트림에 바이트배열을 쓰고 플러시..

                cryptoStream.Write(plainBytes, 0, plainBytes.Length);

                cryptoStream.FlushFinalBlock();

 

                //메모리스트림에 담겨있는 암호화된 바이트배열을 담음

                byte[] encryptBytes = memoryStream.ToArray();

 

                //베이스64로 변환

                string encryptString = Convert.ToBase64String(encryptBytes);

 

                //스트림 닫기.

                cryptoStream.Close();

                memoryStream.Close();

 

                return encryptString;

            }

            catch (Exception)

            {

                return null;

            }

        }

 

        //AES256 복호화.., CBC, PKCS7, 예외발생하면 null

        public static string decryptAES256(string encrypt)

        {

            try

            {

                //base64를 바이트로 변환

                byte[] encryptBytes = Convert.FromBase64String(encrypt);

                //byte[] encryptBytes = Encoding.UTF8.GetBytes(encryptString);

 

                //레인달 알고리듬

                RijndaelManaged rm = new RijndaelManaged();

                //자바에서 사용한 운용모드와 패딩방법 일치시킴(AES/CBC/PKCS5Padding)

                rm.Mode = CipherMode.CBC;

                rm.Padding = PaddingMode.PKCS7;

                rm.KeySize = 256;

 

                //메모리스트림 생성

                MemoryStream memoryStream = new MemoryStream(encryptBytes);

 

                //key, iv값 정의

                ICryptoTransform decryptor = rm.CreateDecryptor(Encoding.UTF8.GetBytes(KEY_256), Encoding.UTF8.GetBytes(KEY_128));

                //크립토스트림을 키와 IV값으로 메모리스트림을 이용하여 생성

                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);

 

                //복호화된 데이터를 담을 바이트 배열을 선언한다.

                byte[] plainBytes = new byte[encryptBytes.Length];

 

                int plainCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);

 

                //복호화된 바이트 배열을 string으로 변환

                string plainString = Encoding.UTF8.GetString(plainBytes, 0, plainCount);

 

                //스트림 닫기.

                cryptoStream.Close();

                memoryStream.Close();

 

                return plainString;

            }

            catch (Exception)

            {

                return null;

            }

        }

 

        //SHA256 해쉬 함수 암호화.., 예외발생하면 null

        public static string encryptSHA256(string plain)

        {

            try

            {

                //바이트로 변환

                byte[] plainBytes = Encoding.UTF8.GetBytes(plain);

 

                SHA256Managed sm = new SHA256Managed();

 

                byte[] encryptBytes = sm.ComputeHash(plainBytes);

 

                //hex.. 16진수

                //string encryptString = BitConverter.ToString(encryptBytes).Replace("-", "").ToLower();

 

                //base64

                string encryptString = Convert.ToBase64String(encryptBytes);

 

                return encryptString;

            }

            catch (Exception)

            {

                return null;

            }

        }

    }

}

 

실행결과

 



출처: http://aircook.tistory.com/entry/AES-SHA-암호화-3-C [aircook의 잡동사니]