-
Notifications
You must be signed in to change notification settings - Fork 1
/
Misc.cs
398 lines (352 loc) · 15.2 KB
/
Misc.cs
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
using Nfu.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Nfu
{
public sealed class LineSeparator : UserControl
{
/// <summary>
/// Constructor.
/// </summary>
public LineSeparator()
{
Paint += PaintLineSeparator;
MaximumSize = new Size(2000, 2);
MinimumSize = new Size(0, 2);
TabStop = false;
Width = 350;
}
/// <summary>
/// A simple seperator control.
/// </summary>
private void PaintLineSeparator(object sender, PaintEventArgs e)
{
var g = e.Graphics;
g.DrawLine(Pens.DarkGray, new Point(0, 0), new Point(Width, 0));
g.DrawLine(Pens.White, new Point(0, 1), new Point(Width, 1));
}
}
public static class Misc
{
[DllImport("user32.dll")]
public static extern int SetForegroundWindow(IntPtr handle);
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr handle, int id, int mode, Keys key);
[DllImport("user32")]
public static extern uint SendMessage(IntPtr handle, uint msg, uint wParam, uint lParam);
[DllImport("advapi32.dll")]
public static extern bool LogonUser(string username, string domain, string password, int logonType, int logonProvider, ref IntPtr token);
private delegate void HotKeyPass();
private class HotKeyWndProc : NativeWindow
{
public HotKeyPass HotKeyPass;
public int WParam = 10000;
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312 && m.WParam.ToInt32() == WParam)
{
HotKeyPass?.Invoke();
}
base.WndProc(ref m);
}
}
/// <summary>
/// Bind a hotkey to a method.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="method">The method.</param>
/// <param name="id">The bind ID.</param>
/// <param name="handle">The handle.</param>
public static bool RegisterHotKey(Keys key, Action method, int id, IntPtr handle)
{
var hotKeyWnd = new HotKeyWndProc();
if (!RegisterHotKey(handle, id, 0, key))
{
HandleError(new Win32Exception(string.Format(Resources.RegisterHotKeyFailed, key)), Resources.RegisterHotKey);
return false;
}
try
{
hotKeyWnd.HotKeyPass = new HotKeyPass(method);
hotKeyWnd.WParam = id;
hotKeyWnd.AssignHandle(handle);
return true;
}
catch
{
hotKeyWnd.ReleaseHandle();
return false;
}
}
/// <summary>
/// Handle an exception.
/// </summary>
/// <param name="err">The exception.</param>
/// <param name="name">Name of the exception.</param>
/// <param name="show">Whether the exception should be shown in the status bar.</param>
/// <param name="type">The type of error, Error is considered fatal and will close the program.</param>
public static void HandleError(Exception err, string name, bool show = true, EventLogEntryType type = EventLogEntryType.Warning)
{
try
{
if (Settings.Default.Debug)
{
EventLog.WriteEntry(Resources.AppName, $"[{name}]: {err.Message}\n\n{err.StackTrace}", type);
}
}
catch
{
MessageBox.Show(Resources.LogNotWriteable, Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
Settings.Default.Debug = false;
}
if (type == EventLogEntryType.Error)
{
MessageBox.Show(Resources.FatalError, Resources.FatalErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
else if (show)
{
Program.FormCore.toolStripStatus.Text = HandleErrorStatusText(name);
}
}
/// <summary>
/// Get the error text for the status bar.
/// </summary>
/// <param name="name">The name of the error.</param>
/// <returns>The error text.</returns>
public static string HandleErrorStatusText(string name)
{
return string.Format(Resources.Failed, name);
}
/// <summary>
/// Get the remote file name.
/// This will remove unsafe characters and increaste the upload count.
/// </summary>
/// <param name="filename">The file name.</param>
/// <returns>The remote filename.</returns>
public static string GetRemoteFileName(string filename)
{
var extension = Path.GetExtension(filename);
filename = Path.GetFileNameWithoutExtension(filename);
switch (Settings.Default.Filename)
{
case 0:
filename = Regex.Replace(filename.Replace(' ', '_'), "[^a-zA-Z_\\.]*$", string.Empty).Trim();
break;
case 1:
filename = GetGeneratedFileNameByPattern(Settings.Default.GeneratedFileNamePattern);
break;
}
return filename + extension;
}
/// <summary>
/// Enable or disable all controls except progressUpload on CoreForm.
/// </summary>
/// <param name="status">True to enable, false to disable.</param>
public static void SetControlStatus(bool status)
{
foreach (Control control in Program.FormCore.Controls)
if (control.Name != "progressUpload" && control.Name != "updateButton") control.Enabled = status;
// Only enable the update button if status is true and there is an update available
Program.FormCore.buttonUpdate.Enabled = (status && Program.FormCore.UpdateAvailable);
}
/// <summary>
/// Show a balloon with some info.
/// </summary>
/// <param name="title">The title.</param>
/// <param name="text">The message.</param>
/// <param name="icon">The icon.</param>
public static void ShowInfo(string title, string text, ToolTipIcon icon = ToolTipIcon.Info)
{
if (Program.FormCore.WindowState != FormWindowState.Minimized)
return;
Program.FormCore.notifyIconNfu.ShowBalloonTip(1000, title, text, icon);
}
/// <summary>
/// Encrypt a password.
/// </summary>
/// <param name="plainPassword">The password in plain text.</param>
/// <returns>The encrypted password.</returns>
public static string Encrypt(string plainPassword)
{
if (string.IsNullOrEmpty(plainPassword))
{
return string.Empty;
}
try
{
var initVectorBytes = Encoding.ASCII.GetBytes(Settings.Default.IV);
var saltValueBytes = Encoding.ASCII.GetBytes(Settings.Default.SaltValue);
var plainTextBytes = Encoding.UTF8.GetBytes(plainPassword);
var password = new Rfc2898DeriveBytes(Settings.Default.PassPhrase, saltValueBytes, Settings.Default.PasswordIterations);
var keyBytes = password.GetBytes(Settings.Default.KeySize / 8);
var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
var memoryStream = new MemoryStream();
var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
catch (Exception e)
{
HandleError(e, Resources.Encrypt);
return null;
}
}
/// <summary>
/// Decrypt a password.
/// </summary>
/// <param name="encryptedPassword">The encrypted password.</param>
/// <returns>The password in plain text.</returns>
public static string Decrypt(string encryptedPassword)
{
if (string.IsNullOrEmpty(encryptedPassword))
{
return string.Empty;
}
try
{
var initVectorBytes = Encoding.ASCII.GetBytes(Settings.Default.IV);
var saltValueBytes = Encoding.ASCII.GetBytes(Settings.Default.SaltValue);
var cipherTextBytes = Convert.FromBase64String(encryptedPassword);
var password = new Rfc2898DeriveBytes(Settings.Default.PassPhrase, saltValueBytes, Settings.Default.PasswordIterations);
var keyBytes = password.GetBytes(Settings.Default.KeySize / 8);
var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
var memoryStream = new MemoryStream(cipherTextBytes);
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
catch (Exception e)
{
HandleError(e, Resources.Decrypt);
return null;
}
}
/// <summary>
/// Check if a certificate is valid.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="certificate">The certificate.</param>
/// <param name="chain">The chain.</param>
/// <param name="sslPolicyErrors">The errors.</param>
/// <returns>True if valid, false if invalid.</returns>
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
var validatedCertificate = true;
// Check if SSL errors occured and if certificate hash is not trusted
if (sslPolicyErrors != SslPolicyErrors.None && Settings.Default.TrustedHash != certificate.GetCertHashString())
{
if (MessageBox.Show(string.Format(Resources.UntrustedCertificate, certificate.Subject, certificate.Issuer, certificate.GetCertHashString()), Resources.UntrustedCertificateTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
Settings.Default.TrustedHash = certificate.GetCertHashString();
}
else
{
validatedCertificate = false;
}
}
return validatedCertificate;
}
/// <summary>
/// Get a temporary filename, displaying a warning when the temporary folder is full.
/// </summary>
/// <returns>The temporary filename, or null on failure.</returns>
public static string GetTempFileName(int iteration = 1)
{
try
{
return Path.GetTempFileName();
}
catch (IOException)
{
var temporaryFolderDialog = MessageBox.Show(string.Format(Resources.TemporaryFolderFull, iteration, Settings.Default.TemporaryFolderRetries),
Resources.TemporaryFolderFullTitle, MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
if (temporaryFolderDialog == DialogResult.Retry && iteration <= Settings.Default.TemporaryFolderRetries)
{
return GetTempFileName(iteration + 1);
}
else if (temporaryFolderDialog == DialogResult.Cancel)
{
return null;
}
}
return null;
}
/// <summary>
/// Get a generated filename by a pattern.
/// </summary>
/// <param name="pattern">The pattern.</param>
/// <returns>The generated filename.</returns>
public static string GetGeneratedFileNameByPattern(string pattern)
{
var randomNumber = new Random();
var output = new StringBuilder();
const string availableRandomCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var replaceDictionary = new Dictionary<char, string>
{
{ 's', DateTime.Now.ToString("ss") },
{ 'm', DateTime.Now.ToString("mm") },
{ 'h', DateTime.Now.ToString("HH") },
{ 'D', DateTime.Now.ToString("dd") },
{ 'M', DateTime.Now.ToString("MM") },
{ 'Y', DateTime.Now.ToString("yyyy") }
};
var nextIsSpecialChar = false;
var randomCharacterIndex = 0;
var randomCharacterCount = pattern.Count(c => c == '?');
var randomCharacters = new string(Enumerable.Repeat(availableRandomCharacters, randomCharacterCount).Select(s => s[randomNumber.Next(s.Length)]).ToArray());
foreach (var character in pattern)
{
if (character == '%' && !nextIsSpecialChar)
{
nextIsSpecialChar = true;
continue;
}
if (nextIsSpecialChar)
{
switch (character)
{
case '?':
output.Append(randomCharacters[randomCharacterIndex++]);
break;
case 'C':
output.Append(++Settings.Default.Count);
break;
default:
output.Append(replaceDictionary.ContainsKey(character)
? replaceDictionary[character]
: $"%{character}");
break;
}
}
else
{
output.Append(character);
}
nextIsSpecialChar = false;
}
return output.ToString();
}
}
}