-
Notifications
You must be signed in to change notification settings - Fork 28
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #221 from Lombiq/issue/LMBQ-249
LMBQ-249: Adding GenerateRandomPassword helper
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
Lombiq.HelpfulLibraries.OrchardCore/Users/PasswordHelper.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Security.Cryptography; | ||
|
||
namespace Lombiq.HelpfulLibraries.OrchardCore.Users; | ||
|
||
public static class PasswordHelper | ||
{ | ||
/// <summary> | ||
/// Generates a <paramref name="minLength"/> long random password. | ||
/// </summary> | ||
public static string GenerateRandomPassword(int minLength) | ||
{ | ||
const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-="; // #spell-check-ignore-line | ||
|
||
using var rng = RandomNumberGenerator.Create(); | ||
const string digits = "0123456789"; | ||
const string lowerChars = "abcdefghijklmnopqrstuvwxyz"; // #spell-check-ignore-line | ||
const string upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // #spell-check-ignore-line | ||
const string specialChars = "!@#$%^&*()_+-="; | ||
|
||
var passwordChars = new List<char> | ||
{ | ||
digits[rng.Next(0, digits.Length)], | ||
lowerChars[rng.Next(0, lowerChars.Length)], | ||
upperChars[rng.Next(0, upperChars.Length)], | ||
specialChars[rng.Next(0, specialChars.Length)], | ||
}; | ||
|
||
while (passwordChars.Count < minLength) | ||
{ | ||
passwordChars.Add(validChars[rng.Next(0, validChars.Length)]); | ||
} | ||
|
||
passwordChars = passwordChars.OrderBy(c => rng.Next(0, int.MaxValue)).ToList(); | ||
string password = new(passwordChars.ToArray()); | ||
|
||
return password; | ||
} | ||
} |