프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / License.cs @ 561be905

이력 | 보기 | 이력해설 | 다운로드 (13.9 KB)

1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using System.Security.Cryptography;
7
using System.IO;
8
using Microsoft.Win32;
9
using System.Net.NetworkInformation;
10
using Converter.SPPID.Form;
11
using System.Windows.Forms;
12
using Converter.SPPID.Properties;
13
using System.Net;
14
using JWT;
15
using JWT.Algorithms;
16
using JWT.Serializers;
17
using JWT.Exceptions;
18
using Newtonsoft.Json;
19

    
20
namespace DOFTECH.License
21
{
22
    public class LicenseDTO
23
    {
24
        /// <summary>
25
        /// 라이센스 고유 값
26
        /// </summary>
27
        public int uid { get; set; }
28

    
29
        /// <summary>
30
        /// MAC 주소
31
        /// </summary>
32
        public string mac { get; set; }
33

    
34
        /// <summary>
35
        /// 메일 주소
36
        /// </summary>
37
        public string email { get; set; }
38

    
39
        /// <summary>
40
        /// 어플리케이션
41
        /// </summary>
42
        public string app { get; set; }
43

    
44
        /// <summary>
45
        /// 라이센스 코드
46
        /// </summary>
47
        public string code { get; set; }
48

    
49
        /// <summary>
50
        /// api name.
51
        /// </summary>
52
        public string api { get; set; }
53

    
54
        /// <summary>
55
        /// 만료 시간.
56
        /// </summary>
57
        public string expiration_date { get; set; }
58

    
59
        /// <summary>
60
        /// 만료 시간.
61
        /// </summary>
62
        public string exp { get; set; }
63

    
64
        /// <summary>
65
        /// License 개수
66
        /// </summary>
67
        public int count { get; set; }
68
    }
69

    
70
    public class LicenseReturn
71
    {
72
        /// <summary>
73
        /// STATUS
74
        /// </summary>
75
        public bool success { get; set; }
76

    
77
        /// <summary>
78
        /// CODE
79
        /// </summary>
80
        public int code { get; set; }
81

    
82
        /// <summary>
83
        /// MSG
84
        /// </summary>
85
        public string msg { get; set; }
86

    
87
        /// <summary>
88
        /// DATA
89
        /// </summary>
90
        public string data { get; set; }
91
    }
92

    
93
    public static class License
94
    {
95
        //public static bool IsEnabled()
96
        //{
97
        //    bool result = false;
98
        //    string path = string.Empty;
99

    
100
        //    try
101
        //    {
102
        //        RegistryKey key = Registry.LocalMachine;
103
        //        RegistryKey software = key.OpenSubKey("SOFTWARE");
104
        //        RegistryKey DOFTECH = software.OpenSubKey("DOFTECH");
105
        //        RegistryKey SPPIDConverter = DOFTECH.OpenSubKey("SPPIDConverter", true);
106
        //        path = SPPIDConverter.GetValue("path") + "licenses.licx";
107
        //        if (File.Exists(path))
108
        //        {
109
        //            string data = File.ReadAllText(path);
110
        //            data = Crypt.decrypt(data, "dof1073#");
111
        //            if (data.StartsWith("Date:"))
112
        //            {
113
        //                data = data.Remove(0, "Date:".Length);
114

    
115
        //                if (string.IsNullOrEmpty(data))
116
        //                {
117
        //                    DateTime dataTime = new DateTime(2000, 1, 1);
118
        //                    DateTime currentTime = DateTime.Now;
119
        //                    if (DateTime.TryParse(Converter.SPPID.Properties.Resources.lic, out dataTime) && DateTime.Compare(dataTime.AddDays(150), currentTime) >= 0)
120
        //                        result = true;
121
        //                }
122
        //            }
123
        //            else if (data.StartsWith("Absolute:"))
124
        //            {
125
        //                data = data.Remove(0, "Absolute:".Length);
126
        //                string macAddress = NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString();
127
        //                if (string.IsNullOrEmpty(data))
128
        //                {
129
        //                    data = "Absolute:" + macAddress;
130
        //                    data = Crypt.encrypt(data, "dof1073#");
131
        //                    File.WriteAllText(path, data);
132
        //                    result = true;
133
        //                }
134
        //                else if (macAddress == data)
135
        //                    result = true;
136
        //            }
137
        //        }
138
        //    }
139
        //    catch (Exception ex)
140
        //    {
141

    
142
        //    }
143

    
144
        //    return result;
145
        //}
146

    
147
        public static bool IsEnabled()
148
        {
149
            bool result = false;
150

    
151
            return true; // skip checking
152

    
153
            try
154
            {
155
                string key = Settings.Default.LicenseKey;
156
                if (!string.IsNullOrEmpty(key))
157
                {
158
                    key = Crypt.decrypt(key, "dof1073#");
159

    
160
                    if (CheckLocalKey(key))
161
                    {
162
                        Settings.Default.LicenseKey = Crypt.encrypt(key, "dof1073#");
163
                        Settings.Default.Save();
164

    
165
                        return true;
166
                    }
167
                }
168
                else
169
                {
170
                    key = "dummy"; // must fail
171
                }
172

    
173
                if (!CheckLicense(key))
174
                {
175
                    var dlg = new LicenseForm();
176
                    if (dlg.ShowDialog() == DialogResult.OK)
177
                    {
178
                        key = dlg.key;
179

    
180
                        if (CheckLocalKey(key))
181
                        {
182
                            Settings.Default.LicenseKey = Crypt.encrypt(key, "dof1073#");
183
                            Settings.Default.Save();
184

    
185
                            return true;
186
                        }
187
                    }
188

    
189
                    if (CheckLicense(key))
190
                    {
191
                        Settings.Default.LicenseKey = Crypt.encrypt(key, "dof1073#");
192
                        Settings.Default.Save();
193

    
194
                        result = true;
195
                    }
196
                    else
197
                    {
198
                        Settings.Default.LicenseKey = Crypt.encrypt("dummy", "dof1073#");
199
                        Settings.Default.Save();
200
                    }
201
                }
202
                else
203
                {
204
                    result = true;
205
                }
206
            }
207
            catch (Exception ex)
208
            {
209
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
210
            }
211

    
212
            return result;
213
        }
214

    
215
        public static bool CheckLocalKey(string key)
216
        {
217
            //return false; // for erase key
218
            try
219
            {
220
                string _key = "Image Drawing to Intelligent Drawing";
221

    
222
                string incoming = key.Replace('_', '/').Replace('-', '+');
223
                switch (key.Length % 4)
224
                {
225
                    case 2: incoming += "=="; break;
226
                    case 3: incoming += "="; break;
227
                }
228
                byte[] bytes = Convert.FromBase64String(incoming);
229
                string originalText = Encoding.ASCII.GetString(bytes);
230

    
231
                string decodeText = "";
232
                //for (int i = 0; i < originalText.Length;  i++)
233
                //{
234
                //    var key_c = _key[i % _key.Length];
235
                //    var dec_c = (char)((256 + originalText[i] - (key_c)) % 256);
236
                //    decodeText += dec_c;
237
                //}
238
                for (int i = 0; i < bytes.Length; i++)
239
                {
240
                    var key_c = _key[i % _key.Length];
241
                    var dec_c = (char)((256 + bytes[i] - (key_c)) % 256);
242
                    decodeText += dec_c;
243
                }
244

    
245
                if (SystemInformation.ComputerName == decodeText)
246
                {
247
                    return true;
248
                }
249
            }
250
            catch (Exception ex)
251
            { 
252
                // local key가 아님
253
            }
254

    
255
            return false;
256
        }
257

    
258
        public static bool CheckLicense(string key)
259
        {
260
            //return false; // for erase key
261
            try
262
            {
263
                const string secret = "795hi#(7qq5&p#f3ysa#n-449h8g_n95olca)b%t23s7!w%v0m";
264

    
265
                if (key != "dummy")
266
                {
267
                    IJsonSerializer serializer = new JsonNetSerializer();
268
                    var provider = new UtcDateTimeProvider();
269
                    IJwtValidator validator = new JwtValidator(serializer, provider);
270
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
271
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric
272
                    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
273
                    var json = decoder.Decode(key, secret, verify: true);
274
                    var licenseDto = JsonConvert.DeserializeObject<LicenseDTO>(json);
275

    
276
                    if (NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString() != licenseDto.mac)
277
                    //if ("00155D0B4A1A" != licenseDto.mac)
278
                    {
279
                        return false;
280
                    }
281

    
282
                    string url = licenseDto.api;
283
                    string responseText = string.Empty;
284

    
285
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
286
                    request.Method = "GET";
287
                    request.Timeout = 5 * 1000;
288
                    request.ContentType = "application/json";
289
                    request.Headers.Add("x-auth-token:" + key);
290

    
291
                    bool validKey = true;
292

    
293
                    using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
294
                    {
295
                        HttpStatusCode status = resp.StatusCode;
296
                        Console.WriteLine(status);
297

    
298
                        Stream respStream = resp.GetResponseStream();
299
                        using (StreamReader sr = new StreamReader(respStream))
300
                        {
301
                            responseText = sr.ReadToEnd();
302
                            var licenseReturn = JsonConvert.DeserializeObject<LicenseReturn>(responseText);
303

    
304
                            if (!licenseReturn.success)
305
                            {
306
                                MessageBox.Show(licenseReturn.msg, "SPPID Converter", MessageBoxButtons.OK, MessageBoxIcon.Warning);
307
                                validKey = false;
308
                            }
309
                        }
310
                    }
311

    
312
                    return validKey;
313
                }
314
            }
315
            catch (Exception ex)
316
            {
317
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
318
            }
319

    
320
            return false;
321
        }
322

    
323
        public static string SHA256Hash(string data)
324
        {
325

    
326
            SHA256 sha = new SHA256Managed();
327
            byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data));
328
            StringBuilder stringBuilder = new StringBuilder();
329
            foreach (byte b in hash)
330
            {
331
                stringBuilder.AppendFormat("{0:x2}", b);
332
            }
333
            return stringBuilder.ToString();
334
        }
335

    
336
        private static void CreateDateLicenseFile()
337
        {
338
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\[Date]licenses.licx";
339
            string data = "Date:";
340
            using (StreamWriter sw = File.CreateText(path))
341
            {
342
                data = Crypt.encrypt(data, "dof1073#");
343
                sw.Write(data);
344
                sw.Close();
345
                sw.Dispose();
346
            }
347
        }
348

    
349
        private static void CreateAbsoluteLicenseFile()
350
        {
351
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\[Absolute]licenses.licx";
352
            string data = "Absolute:";
353
            using (StreamWriter sw = File.CreateText(path))
354
            {
355
                data = Crypt.encrypt(data, "dof1073#");
356
                sw.Write(data);
357
                sw.Close();
358
                sw.Dispose();
359
            }
360
        }
361
    }
362

    
363
    class Crypt
364
    {
365
        public static String encrypt(String text, String password)
366
        {
367
            RijndaelManaged RijndaelCipher = new RijndaelManaged();
368
            byte[] plainText = Encoding.UTF8.GetBytes(text);
369
            byte[] salt = Encoding.UTF8.GetBytes(password);
370
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(password, salt);
371
            ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
372
            MemoryStream memoryStream = new MemoryStream();
373
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
374
            cryptoStream.Write(plainText, 0, plainText.Length);     // 암호화 시작
375
            cryptoStream.FlushFinalBlock();
376
            byte[] cryptBytes = memoryStream.ToArray();
377
            // 스트림을 닫습니다.
378
            memoryStream.Close();
379
            cryptoStream.Close();
380
            String cryptResult = Convert.ToBase64String(cryptBytes);
381
            return cryptResult;     // 암호화 문자열 리턴.
382
        }
383
        public static String decrypt(String text, String password)
384
        {
385
            RijndaelManaged RijndaelCipher = new RijndaelManaged();
386
            byte[] encryptData = Convert.FromBase64String(text);
387
            byte[] salt = Encoding.UTF8.GetBytes(password);
388
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(password, salt);
389
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
390
            MemoryStream memoryStream = new MemoryStream(encryptData);
391
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
392
            byte[] PlainText = new byte[encryptData.Length];
393
            // 복호화 시작
394
            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
395
            memoryStream.Close();
396
            cryptoStream.Close();
397
            // 복호화된 데이터를 문자열로 바꾼다.
398
            string DecryptedData = Encoding.UTF8.GetString(PlainText, 0, DecryptedCount);
399
            // 최종 결과 리턴
400
            return DecryptedData;
401
        }
402
    }
403
}
클립보드 이미지 추가 (최대 크기: 500 MB)