You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StringGenerator.cs 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. namespace Diligent.WebAPI.Business.Helper
  2. {
  3. public static class StringGenerator
  4. {
  5. public static string GenerateRandomPassword(PasswordOptions opts = null)
  6. {
  7. if (opts == null) opts = new PasswordOptions()
  8. {
  9. RequiredLength = 8,
  10. RequiredUniqueChars = 4,
  11. RequireDigit = true,
  12. RequireLowercase = true,
  13. RequireNonAlphanumeric = true,
  14. RequireUppercase = true
  15. };
  16. string[] randomChars = new[] {
  17. "ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase
  18. "abcdefghijkmnopqrstuvwxyz", // lowercase
  19. "0123456789", // digits
  20. "!@$?_-" // non-alphanumeric
  21. };
  22. Random rand = new(Environment.TickCount);
  23. List<char> chars = new List<char>();
  24. if (opts.RequireUppercase)
  25. chars.Insert(rand.Next(0, chars.Count),
  26. randomChars[0][rand.Next(0, randomChars[0].Length)]);
  27. if (opts.RequireLowercase)
  28. chars.Insert(rand.Next(0, chars.Count),
  29. randomChars[1][rand.Next(0, randomChars[1].Length)]);
  30. if (opts.RequireDigit)
  31. chars.Insert(rand.Next(0, chars.Count),
  32. randomChars[2][rand.Next(0, randomChars[2].Length)]);
  33. if (opts.RequireNonAlphanumeric)
  34. chars.Insert(rand.Next(0, chars.Count),
  35. randomChars[3][rand.Next(0, randomChars[3].Length)]);
  36. for (int i = chars.Count; i < opts.RequiredLength
  37. || chars.Distinct().Count() < opts.RequiredUniqueChars; i++)
  38. {
  39. string rcs = randomChars[rand.Next(0, randomChars.Length)];
  40. chars.Insert(rand.Next(0, chars.Count),
  41. rcs[rand.Next(0, rcs.Length)]);
  42. }
  43. return new string(chars.ToArray());
  44. }
  45. }
  46. }