Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LMBQ-249: Adding GenerateRandomPassword helper #221

Merged
merged 1 commit into from
Oct 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}