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.

74 lines
2.6 KiB

1 year ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Common.Helper
  5. {
  6. public class PasswordGenerator
  7. {
  8. public class PasswordOptions
  9. {
  10. public int RequiredLength { get; set; }
  11. public int RequiredUniqueChars { get; set; }
  12. public bool RequireLowercase { get; set; }
  13. public bool RequireDigit { get; set; }
  14. public bool RequireUppercase { get; set; }
  15. public bool RequireNonAlphanumeric { get; set; }
  16. }
  17. public static string GenerateRandomPassword(PasswordOptions opts = null)
  18. {
  19. if (opts == null) opts = new PasswordOptions()
  20. {
  21. RequiredLength = 8,
  22. RequiredUniqueChars = 4,
  23. RequireDigit = true,
  24. RequireLowercase = true,
  25. RequireNonAlphanumeric = true,
  26. RequireUppercase = true
  27. };
  28. string[] randomChars = new[] {
  29. "ABCDEFGHJKMNPQRSTUVWXYZ", // uppercase
  30. "abcdefghjkmnpqrstuvwxyz", // lowercase
  31. "23456789", // digits
  32. "@#" // non-alphanumeric
  33. };
  34. string[] randomChars1 = new[] {
  35. // uppercase
  36. "abcdefghjkmnpqrstuvwxyz", // lowercase
  37. "23456789", // digits
  38. // non-alphanumeric
  39. };
  40. Random rand = new Random();
  41. List<char> chars = new List<char>();
  42. if (opts.RequireUppercase)
  43. chars.Insert(rand.Next(0, chars.Count),
  44. randomChars[0][rand.Next(0, randomChars[0].Length)]);
  45. if (opts.RequireLowercase)
  46. chars.Insert(rand.Next(0, chars.Count),
  47. randomChars[1][rand.Next(0, randomChars[1].Length)]);
  48. if (opts.RequireDigit)
  49. chars.Insert(rand.Next(0, chars.Count),
  50. randomChars[2][rand.Next(0, randomChars[2].Length)]);
  51. if (opts.RequireNonAlphanumeric)
  52. chars.Insert(rand.Next(0, chars.Count),
  53. randomChars[3][rand.Next(0, randomChars[3].Length)]);
  54. for (int i = chars.Count; i < opts.RequiredLength
  55. || chars.Distinct().Count() < opts.RequiredUniqueChars; i++)
  56. {
  57. string rcs = randomChars1[rand.Next(0, randomChars1.Length)];
  58. chars.Insert(rand.Next(0, chars.Count),
  59. rcs[rand.Next(0, rcs.Length)]);
  60. }
  61. return new string(chars.ToArray());
  62. }
  63. }
  64. }