Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

StringGenerator.cs 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. if(opts.RequiredLength < 4)
  17. opts.RequiredLength = 4;
  18. string[] randomChars = new[] {
  19. "ABCDEFGHJKLMNOPQRSTUVWXYZ", // uppercase
  20. "abcdefghijkmnopqrstuvwxyz", // lowercase
  21. "0123456789", // digits
  22. "!@$?_-" // non-alphanumeric
  23. };
  24. Random rand = new(Environment.TickCount);
  25. List<char> chars = new List<char>();
  26. if (opts.RequireUppercase)
  27. chars.Insert(rand.Next(0, chars.Count),
  28. randomChars[0][rand.Next(0, randomChars[0].Length)]);
  29. if (opts.RequireLowercase)
  30. chars.Insert(rand.Next(0, chars.Count),
  31. randomChars[1][rand.Next(0, randomChars[1].Length)]);
  32. if (opts.RequireDigit)
  33. chars.Insert(rand.Next(0, chars.Count),
  34. randomChars[2][rand.Next(0, randomChars[2].Length)]);
  35. if (opts.RequireNonAlphanumeric)
  36. chars.Insert(rand.Next(0, chars.Count),
  37. randomChars[3][rand.Next(0, randomChars[3].Length)]);
  38. for (int i = chars.Count; i < opts.RequiredLength
  39. || chars.Distinct().Count() < opts.RequiredUniqueChars; i++)
  40. {
  41. string rcs = randomChars[rand.Next(0, randomChars.Length)];
  42. chars.Insert(rand.Next(0, chars.Count),
  43. rcs[rand.Next(0, rcs.Length)]);
  44. }
  45. return new string(chars.ToArray());
  46. }
  47. }
  48. }