본문 바로가기

others

AES, SHA 암호화 3, C#

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

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


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

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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(0128 / 8);
 
        //256bit (32자리)
        private static readonly string KEY_256 = KEY.Substring(0256 / 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;
            }
        }
    }
}
cs


행결과

 

'others' 카테고리의 다른 글

AES, SHA 암호화 5, Swift  (0) 2016.04.21
AES, SHA 암호화 4, T-SQL  (0) 2015.08.26
AES, SHA 암호화 2, PL/SQL  (0) 2015.08.26
AES, SHA 암호화 1, JAVA  (1) 2015.08.26
facebook note에 있던 잡다한것들..  (0) 2013.06.03