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.

81 lines
2.7 KiB

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