Skip to content

Commit

Permalink
Merge pull request #221 from Lombiq/issue/LMBQ-249
Browse files Browse the repository at this point in the history
LMBQ-249: Adding GenerateRandomPassword helper
  • Loading branch information
DemeSzabolcs authored Oct 18, 2023
2 parents d4acb75 + be0b402 commit 6314020
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Lombiq.HelpfulLibraries.OrchardCore/Users/PasswordHelper.cs
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;
}
}

0 comments on commit 6314020

Please sign in to comment.