-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurityExtension.cs
More file actions
270 lines (220 loc) · 9.92 KB
/
SecurityExtension.cs
File metadata and controls
270 lines (220 loc) · 9.92 KB
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Extensions
{
public static class SecurityExtension
{
/// <summary>
/// Supported hash algorithms
/// </summary>
public enum eHashType
{
HMAC, HMACMD5, HMACSHA1, HMACSHA256, HMACSHA384, HMACSHA512, MACTripleDES, MD5, RIPEMD160, SHA1, SHA256, SHA384, SHA512
}
/// <summary>
/// Encryptes a string using the supplied key. Encoding is done using RSA encryption.
/// </summary>
/// <param name="stringToEncrypt">String that must be encrypted.</param>
/// <param name="key">Encryptionkey.</param>
/// <returns>A string representing a byte array separated by a minus sign.</returns>
/// <exception cref="ArgumentException">Occurs when stringToEncrypt or key is null or empty.</exception>
public static string Encrypt(this string stringToEncrypt, string key)
{
if (string.IsNullOrEmpty(stringToEncrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
}
CspParameters cspp = new CspParameters();
cspp.KeyContainerName = key;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);
return BitConverter.ToString(bytes);
}
/// <summary>
/// Decryptes a string using the supplied key. Decoding is done using RSA encryption.
/// </summary>
/// <param name="stringToDecrypt">String that must be decrypted.</param>
/// <param name="key">Decryptionkey.</param>
/// <returns>The decrypted string or null if decryption failed.</returns>
/// <exception cref="ArgumentException">Occurs when stringToDecrypt or key is null or empty.</exception>
public static string Decrypt(this string stringToDecrypt, string key)
{
string result = null;
if (string.IsNullOrEmpty(stringToDecrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
}
try
{
CspParameters cspp = new CspParameters();
cspp.KeyContainerName = key;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, StringSplitOptions.None);
byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));
byte[] bytes = rsa.Decrypt(decryptByteArray, true);
result = System.Text.UTF8Encoding.UTF8.GetString(bytes);
}
finally
{
// no need for further processing
}
return result;
}
private static byte[] GetHash(string input, eHashType hash)
{
byte[] inputBytes = Encoding.ASCII.GetBytes(input);
switch (hash)
{
case eHashType.HMAC:
return HMAC.Create().ComputeHash(inputBytes);
case eHashType.HMACMD5:
return HMACMD5.Create().ComputeHash(inputBytes);
case eHashType.HMACSHA1:
return HMACSHA1.Create().ComputeHash(inputBytes);
case eHashType.HMACSHA256:
return HMACSHA256.Create().ComputeHash(inputBytes);
case eHashType.HMACSHA384:
return HMACSHA384.Create().ComputeHash(inputBytes);
case eHashType.HMACSHA512:
return HMACSHA512.Create().ComputeHash(inputBytes);
case eHashType.MACTripleDES:
return MACTripleDES.Create().ComputeHash(inputBytes);
case eHashType.MD5:
return MD5.Create().ComputeHash(inputBytes);
case eHashType.RIPEMD160:
return RIPEMD160.Create().ComputeHash(inputBytes);
case eHashType.SHA1:
return SHA1.Create().ComputeHash(inputBytes);
case eHashType.SHA256:
return SHA256.Create().ComputeHash(inputBytes);
case eHashType.SHA384:
return SHA384.Create().ComputeHash(inputBytes);
case eHashType.SHA512:
return SHA512.Create().ComputeHash(inputBytes);
default:
return inputBytes;
}
}
/// <summary>
/// Computes the hash of the string using a specified hash algorithm
/// </summary>
/// <param name="input">The string to hash</param>
/// <param name="hashType">The hash algorithm to use</param>
/// <returns>The resulting hash or an empty string on error</returns>
public static string ComputeHash(this string input, eHashType hashType)
{
try
{
byte[] hash = GetHash(input, hashType);
StringBuilder ret = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
ret.Append(hash[i].ToString("x2"));
return ret.ToString();
}
catch
{
return string.Empty;
}
}
/// <summary>
/// Converts a string into a "SecureString"
/// </summary>
/// <param name="str">Input String</param>
/// <returns></returns>
public static System.Security.SecureString ToSecureString(this String str)
{
System.Security.SecureString secureString = new System.Security.SecureString();
foreach (Char c in str)
secureString.AppendChar(c);
return secureString;
}
/// <summary>
/// Convert a input string to a byte array and compute the hash.
/// </summary>
/// <param name="value">Input string.</param>
/// <returns>Hexadecimal string.</returns>
public static string ToMd5Hash(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
using (MD5 md5 = new MD5CryptoServiceProvider())
{
byte[] originalBytes = ASCIIEncoding.Default.GetBytes(value);
byte[] encodedBytes = md5.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes).Replace("-", string.Empty);
}
}
/// <summary>
/// Calculates the SHA1 hash of the supplied string and returns a base 64 string.
/// </summary>
/// <param name="stringToHash">String that must be hashed.</param>
/// <returns>The hashed string or null if hashing failed.</returns>
/// <exception cref="ArgumentException">Occurs when stringToHash or key is null or empty.</exception>
public static string GetSHA1Hash(this string stringToHash)
{
if (string.IsNullOrEmpty(stringToHash))
{
throw new ArgumentException("An empty string value cannot be hashed.");
}
Byte[] data = System.Text.Encoding.UTF8.GetBytes(stringToHash);
Byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(data);
return Convert.ToBase64String(hash);
}
/// <summary>
/// Read and get MD5 hash value of any given filename.
/// </summary>
/// <param name="filename">full path and filename</param>
/// <returns>lowercase MD5 hash value</returns>
public static string GetMD5(this string filename)
{
string result = string.Empty;
string hashData;
FileStream fileStream;
MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
try
{
fileStream = GetFileStream(filename);
byte[] arrByteHashValue = md5Provider.ComputeHash(fileStream);
fileStream.Close();
hashData = BitConverter.ToString(arrByteHashValue).Replace("-", "");
result = hashData;
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
}
return (result.ToLower());
}
private static FileStream GetFileStream(string pathName)
{
return (new FileStream(pathName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
}
public static bool IsStrongPassword(this string s)
{
bool isStrong = Regex.IsMatch(s, @"[\d]");
if (isStrong) isStrong = Regex.IsMatch(s, @"[a-z]");
if (isStrong) isStrong = Regex.IsMatch(s, @"[A-Z]");
if (isStrong) isStrong = Regex.IsMatch(s, @"[\s~!@#\$%\^&\*\(\)\{\}\|\[\]\\:;'?,.`+=<>\/]");
if (isStrong) isStrong = s.Length > 7;
return isStrong;
}
}
}