-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenerators.cs
executable file
·369 lines (320 loc) · 14.8 KB
/
Generators.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
// // ***********************************************************************
// // Solution : Inno.Api.v2
// // Assembly : FCS.Lib.Utility
// // Filename : Generators.cs
// // Created : 2025-01-03 14:01
// // Last Modified By : dev
// // Last Modified On : 2025-01-04 11:01
// // ***********************************************************************
// // <copyright company="Frede Hundewadt">
// // Copyright (C) 2010-2025 Frede Hundewadt
// // This program is free software: you can redistribute it and/or modify
// // it under the terms of the GNU Affero General Public License as
// // published by the Free Software Foundation, either version 3 of the
// // License, or (at your option) any later version.
// //
// // This program is distributed in the hope that it will be useful,
// // but WITHOUT ANY WARRANTY; without even the implied warranty of
// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// // GNU Affero General Public License for more details.
// //
// // You should have received a copy of the GNU Affero General Public License
// // along with this program. If not, see [https://www.gnu.org/licenses]
// // </copyright>
// // <summary></summary>
// // ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
namespace FCS.Lib.Utility;
/// <summary>
/// Provides utility methods for generating various types of random strings, numbers, and other data.
/// </summary>
public static class Generators
{
/// <summary>
/// Generates a short URL string with a default length of 8 characters.
/// </summary>
/// <returns>A randomly generated short URL string.</returns>
public static string ShortUrlGenerator()
{
return ShortUrlGenerator(8);
}
/// <summary>
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string ShortUrlGenerator(int length)
{
// <remarks>derived from https://sourceforge.net/projects/shorturl-dotnet/</remarks>
const string charsLower = "abcdefghijklmnopqrstuvwxyz";
const string charsUpper = "ABCDFEGHJKLMNPQRSTUVWXYZ";
const string charsNumeric = "123456789";
// Create a local array containing supported short-url characters
// grouped by types.
var charGroups = new[]
{
charsLower.ToCharArray(),
charsUpper.ToCharArray(),
charsNumeric.ToCharArray()
};
// Use this array to track the number of unused characters in each
// character group.
var charsLeftInGroup = new int[charGroups.Length];
// Initially, all characters in each group are not used.
for (var i = 0; i < charsLeftInGroup.Length; i++)
charsLeftInGroup[i] = charGroups[i].Length;
// Use this array to track (iterate through) unused character groups.
var leftGroupsOrder = new int[charGroups.Length];
// Initially, all character groups are not used.
for (var i = 0; i < leftGroupsOrder.Length; i++)
leftGroupsOrder[i] = i;
// Using our private random number generator
var random = RandomFromRngCrypto();
// This array will hold short-url characters.
// Allocate appropriate memory for the short-url.
var shortUrl = new char[random.Next(length, length)];
// Index of the last non-processed group.
var lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
// Generate short-url characters one at a time.
for (var i = 0; i < shortUrl.Length; i++)
{
// If only one character group remained unprocessed, process it;
// otherwise, pick a random character group from the unprocessed
// group list. To allow a special character to appear in the
// first position, increment the second parameter of the Next
// function call by one, i.e. lastLeftGroupsOrderIdx + 1.
int nextLeftGroupsOrderIdx;
if (lastLeftGroupsOrderIdx == 0)
nextLeftGroupsOrderIdx = 0;
else
nextLeftGroupsOrderIdx = random.Next(0,
lastLeftGroupsOrderIdx);
// Get the actual index of the character group, from which we will
// pick the next character.
var nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];
// Get the index of the last unprocessed characters in this group.
var lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;
// If only one unprocessed character is left, pick it; otherwise,
// get a random character from the unused character list.
var nextCharIdx = lastCharIdx == 0 ? 0 : random.Next(0, lastCharIdx + 1);
// Add this character to the short-url.
shortUrl[i] = charGroups[nextGroupIdx][nextCharIdx];
// If we processed the last character in this group, start over.
if (lastCharIdx == 0)
{
charsLeftInGroup[nextGroupIdx] =
charGroups[nextGroupIdx].Length;
}
// There are more unprocessed characters left.
else
{
// Swap processed character with the last unprocessed character
// so that we don't pick it until we process all characters in
// this group.
if (lastCharIdx != nextCharIdx)
(charGroups[nextGroupIdx][lastCharIdx], charGroups[nextGroupIdx][nextCharIdx]) = (
charGroups[nextGroupIdx][nextCharIdx], charGroups[nextGroupIdx][lastCharIdx]);
// Decrement the number of unprocessed characters in
// this group.
charsLeftInGroup[nextGroupIdx]--;
}
// If we processed the last group, start all over.
if (lastLeftGroupsOrderIdx == 0)
{
lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
}
// There are more unprocessed groups left.
else
{
// Swap processed group with the last unprocessed group
// so that we don't pick it until we process all groups.
if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
(leftGroupsOrder[lastLeftGroupsOrderIdx], leftGroupsOrder[nextLeftGroupsOrderIdx]) = (
leftGroupsOrder[nextLeftGroupsOrderIdx], leftGroupsOrder[lastLeftGroupsOrderIdx]);
// Decrement the number of unprocessed groups.
lastLeftGroupsOrderIdx--;
}
}
// Convert password characters into a string and return the result.
return new string(shortUrl);
}
/// <summary>
/// Generates a username based on the specified options or default settings.
/// </summary>
/// <param name="options">
/// An instance of <see cref="StringOptions" /> specifying the rules for generating the username.
/// If <c>null</c>, default options will be used, requiring a length of 16 characters,
/// at least one digit, one lowercase letter, one uppercase letter, and four unique characters.
/// </param>
/// <returns>A randomly generated username string that adheres to the specified or default options.</returns>
public static string GenerateUsername(StringOptions options = null)
{
options ??= new StringOptions
{
RequiredLength = 16,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
RequiredUniqueChars = 4,
RequireNonLetterOrDigit = false,
RequireNonAlphanumeric = false
};
return GenerateRandomString(options);
}
/// <summary>
/// Generates a random password based on the specified options or default settings.
/// </summary>
/// <param name="options">
/// An instance of <see cref="StringOptions" /> that specifies the password requirements.
/// If <c>null</c>, default options will be used, which include:
/// <list type="bullet">
/// <item>RequiredLength: 16</item>
/// <item>RequireDigit: true</item>
/// <item>RequireLowercase: true</item>
/// <item>RequireUppercase: true</item>
/// <item>RequiredUniqueChars: 8</item>
/// <item>RequireNonLetterOrDigit: false</item>
/// <item>RequireNonAlphanumeric: false</item>
/// </list>
/// </param>
/// <returns>
/// A randomly generated password that satisfies the provided or default requirements.
/// </returns>
public static string GeneratePassword(StringOptions options = null)
{
options ??= new StringOptions
{
RequiredLength = 16,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
RequiredUniqueChars = 8,
RequireNonLetterOrDigit = false,
RequireNonAlphanumeric = false
};
return GenerateRandomString(options);
}
/// <summary>
/// Generates a random text string of the specified length, alternating between consonants and vowels.
/// </summary>
/// <param name="length">The desired length of the generated text.</param>
/// <returns>A randomly generated string of the specified length.</returns>
public static string GenerateRandomText(int length)
{
const string consonants = "bcdfghjklmnprstvxzBDFGHJKLMNPRSTVXZ";
const string vowels = "aeiouyAEIOUY";
var rndString = "";
var randomNum = RandomFromRngCrypto();
while (rndString.Length < length)
{
rndString += consonants[randomNum.Next(consonants.Length)];
if (rndString.Length < length)
rndString += vowels[randomNum.Next(vowels.Length)];
}
return rndString;
}
/// <summary>
/// Generates a random number of the specified length using cryptographic randomness.
/// </summary>
/// <param name="length">The length of the random number to generate.</param>
/// <returns>A random integer of the specified length.</returns>
public static int GenerateRandomNumber(int length)
{
const string digits = "123456789";
var rndString = "";
var randomNum = RandomFromRngCrypto();
while (rndString.Length < length) rndString += digits[randomNum.Next(digits.Length)];
return Convert.ToInt32(rndString);
}
/// <summary>
/// Generates a random string based on the specified options.
/// </summary>
/// <param name="options">
/// The <see cref="StringOptions" /> object that specifies the requirements for the generated string.
/// If not provided, default options will be used.
/// </param>
/// <returns>
/// A randomly generated string that meets the specified criteria.
/// </returns>
/// <remarks>
/// The generated string can include uppercase letters, lowercase letters, digits, and non-alphanumeric characters,
/// depending on the provided options.
/// </remarks>
public static string GenerateRandomString(StringOptions options = null)
{
options ??= new StringOptions
{
RequiredLength = 16,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
RequiredUniqueChars = 4,
RequireNonLetterOrDigit = true,
RequireNonAlphanumeric = true
};
var randomChars = new[]
{
"ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase
"abcdefghijkmnopqrstuvwxyz", // lowercase
"0123456789", // digits
"!@$?_-" // non-alphanumeric
};
// Using our private random number generator
var rand = RandomFromRngCrypto();
var chars = new List<char>();
if (options.RequireUppercase)
chars.Insert(rand.Next(0, chars.Count),
randomChars[0][rand.Next(0, randomChars[0].Length)]);
if (options.RequireLowercase)
chars.Insert(rand.Next(0, chars.Count),
randomChars[1][rand.Next(0, randomChars[1].Length)]);
if (options.RequireDigit)
chars.Insert(rand.Next(0, chars.Count),
randomChars[2][rand.Next(0, randomChars[2].Length)]);
if (options.RequireNonAlphanumeric)
chars.Insert(rand.Next(0, chars.Count),
randomChars[3][rand.Next(0, randomChars[3].Length)]);
var rcs = randomChars[rand.Next(0, randomChars.Length)];
for (var i = chars.Count;
i < options.RequiredLength
|| chars.Distinct().Count() < options.RequiredUniqueChars;
i++)
chars.Insert(rand.Next(0, chars.Count),
rcs[rand.Next(0, rcs.Length)]);
return new string(chars.ToArray());
}
/// <summary>
/// Generates a new instance of <see cref="System.Random" /> seeded with a cryptographically secure random value.
/// </summary>
/// <remarks>
/// This method uses <see cref="System.Security.Cryptography.RNGCryptoServiceProvider" /> to generate a secure seed
/// value,
/// ensuring that the resulting random number generator produces less predictable sequences compared to the default
/// implementation.
/// </remarks>
/// <returns>
/// A new instance of <see cref="System.Random" /> seeded with a cryptographically secure random value.
/// </returns>
public static Random RandomFromRngCrypto()
{
// As the default Random is based on the current time
// so it produces the same "random" number within a second
// Use a crypto service to create the seed value
// 4-byte array to fill with random bytes
var randomBytes = new byte[4];
// Generate 4 random bytes.
using (var rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(randomBytes);
}
// Convert 4 bytes into a 32-bit integer value.
var seed = ((randomBytes[0] & 0x7f) << 24) |
(randomBytes[1] << 16) |
(randomBytes[2] << 8) |
randomBytes[3];
// Return a truly randomized random generator
return new Random(seed);
}
}