프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / SPPIDConverter / License.cs @ b1d18923

이력 | 보기 | 이력해설 | 다운로드 (11.7 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
            try
152
            {
153
                string key = Settings.Default.LicenseKey;
154
                if (!string.IsNullOrEmpty(key))
155
                {
156
                    key = Crypt.decrypt(key, "dof1073#");
157
                }
158
                else
159
                {
160
                    key = "dummy"; // must fail
161
                }
162

    
163
                if (!CheckLicense(key))
164
                {
165
                    var dlg = new LicenseForm();
166
                    if (dlg.ShowDialog() == DialogResult.OK)
167
                    {
168
                        key = dlg.key;
169
                    }
170

    
171
                    if (CheckLicense(key))
172
                    {
173
                        Settings.Default.LicenseKey = Crypt.encrypt(key, "dof1073#");
174
                        Settings.Default.Save();
175

    
176
                        result = true;
177
                    }
178
                    else
179
                    {
180
                        Settings.Default.LicenseKey = Crypt.encrypt("dummy", "dof1073#");
181
                        Settings.Default.Save();
182
                    }
183
                }
184
                else
185
                {
186
                    result = true;
187
                }
188
            }
189
            catch (Exception ex)
190
            {
191

    
192
            }
193

    
194
            return result;
195
        }
196

    
197
        public static bool CheckLicense(string key)
198
        {
199
            // return false; // for erase key
200
            try
201
            {
202
                const string secret = "795hi#(7qq5&p#f3ysa#n-449h8g_n95olca)b%t23s7!w%v0m";
203

    
204
                if (key != "dummy")
205
                {
206
                    IJsonSerializer serializer = new JsonNetSerializer();
207
                    var provider = new UtcDateTimeProvider();
208
                    IJwtValidator validator = new JwtValidator(serializer, provider);
209
                    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
210
                    IJwtAlgorithm algorithm = new HMACSHA256Algorithm(); // symmetric
211
                    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
212
                    var json = decoder.Decode(key, secret, verify: true);
213
                    var licenseDto = JsonConvert.DeserializeObject<LicenseDTO>(json);
214

    
215
                    if (NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString() != licenseDto.mac)
216
                    //if ("00155D0B4A1A" != licenseDto.mac)
217
                    {
218
                        return false;
219
                    }
220

    
221
                    string url = licenseDto.api;
222
                    string responseText = string.Empty;
223

    
224
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
225
                    request.Method = "GET";
226
                    request.Timeout = 5 * 1000;
227
                    request.ContentType = "application/json";
228
                    request.Headers.Add("x-auth-token:" + key);
229

    
230
                    bool validKey = true;
231

    
232
                    using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
233
                    {
234
                        HttpStatusCode status = resp.StatusCode;
235
                        Console.WriteLine(status);
236

    
237
                        Stream respStream = resp.GetResponseStream();
238
                        using (StreamReader sr = new StreamReader(respStream))
239
                        {
240
                            responseText = sr.ReadToEnd();
241
                            var licenseReturn = JsonConvert.DeserializeObject<LicenseReturn>(responseText);
242

    
243
                            if (!licenseReturn.success)
244
                            {
245
                                MessageBox.Show(licenseReturn.msg, "SPPID Converter", MessageBoxButtons.OK, MessageBoxIcon.Warning);
246
                                validKey = false;
247
                            }
248
                        }
249
                    }
250

    
251
                    return validKey;
252
                }
253
            }
254
            catch (Exception ex)
255
            {
256

    
257
            }
258

    
259
            return false;
260
        }
261

    
262
        public static string SHA256Hash(string data)
263
        {
264

    
265
            SHA256 sha = new SHA256Managed();
266
            byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(data));
267
            StringBuilder stringBuilder = new StringBuilder();
268
            foreach (byte b in hash)
269
            {
270
                stringBuilder.AppendFormat("{0:x2}", b);
271
            }
272
            return stringBuilder.ToString();
273
        }
274

    
275
        private static void CreateDateLicenseFile()
276
        {
277
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\[Date]licenses.licx";
278
            string data = "Date:";
279
            using (StreamWriter sw = File.CreateText(path))
280
            {
281
                data = Crypt.encrypt(data, "dof1073#");
282
                sw.Write(data);
283
                sw.Close();
284
                sw.Dispose();
285
            }
286
        }
287

    
288
        private static void CreateAbsoluteLicenseFile()
289
        {
290
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\[Absolute]licenses.licx";
291
            string data = "Absolute:";
292
            using (StreamWriter sw = File.CreateText(path))
293
            {
294
                data = Crypt.encrypt(data, "dof1073#");
295
                sw.Write(data);
296
                sw.Close();
297
                sw.Dispose();
298
            }
299
        }
300
    }
301

    
302
    class Crypt
303
    {
304
        public static String encrypt(String text, String password)
305
        {
306
            RijndaelManaged RijndaelCipher = new RijndaelManaged();
307
            byte[] plainText = Encoding.UTF8.GetBytes(text);
308
            byte[] salt = Encoding.UTF8.GetBytes(password);
309
            PasswordDeriveBytes secretKey = new PasswordDeriveBytes(password, salt);
310
            ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
311
            MemoryStream memoryStream = new MemoryStream();
312
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
313
            cryptoStream.Write(plainText, 0, plainText.Length);     // 암호화 시작
314
            cryptoStream.FlushFinalBlock();
315
            byte[] cryptBytes = memoryStream.ToArray();
316
            // 스트림을 닫습니다.
317
            memoryStream.Close();
318
            cryptoStream.Close();
319
            String cryptResult = Convert.ToBase64String(cryptBytes);
320
            return cryptResult;     // 암호화 문자열 리턴.
321
        }
322
        public static String decrypt(String text, String password)
323
        {
324
            RijndaelManaged RijndaelCipher = new RijndaelManaged();
325
            byte[] encryptData = Convert.FromBase64String(text);
326
            byte[] salt = Encoding.UTF8.GetBytes(password);
327
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(password, salt);
328
            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
329
            MemoryStream memoryStream = new MemoryStream(encryptData);
330
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
331
            byte[] PlainText = new byte[encryptData.Length];
332
            // 복호화 시작
333
            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
334
            memoryStream.Close();
335
            cryptoStream.Close();
336
            // 복호화된 데이터를 문자열로 바꾼다.
337
            string DecryptedData = Encoding.UTF8.GetString(PlainText, 0, DecryptedCount);
338
            // 최종 결과 리턴
339
            return DecryptedData;
340
        }
341
    }
342
}
클립보드 이미지 추가 (최대 크기: 500 MB)