Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.04 KB | None | 0 0
  1. public class PasswordGenerator : IPasswordGenerator
  2. {
  3. private readonly Random _rand = new Random(Environment.TickCount);
  4. private readonly PasswordOptions _passwordOptions;
  5. // private readonly ImmutableArray<string> _randomChars = new ImmutableArray<string>
  6. // {
  7. // "ABCDEFGHJKLMNOPQRSTUVWXYZ",
  8. // "abcdefghijkmnopqrstuvwxyz",
  9. // "0123456789",
  10. // "!@$?_-"
  11. // };
  12. private const string Uppercase = "ABCDEFGHJKLMNOPQRSTUVWXYZ";
  13. private const string Lowercase = "abcdefghijkmnopqrstuvwxyz";
  14. private const string Digits = "0123456789";
  15. private const string Special =
  16.  
  17. public PasswordGenerator(PasswordOptions passwordOptions)
  18. {
  19. _passwordOptions = passwordOptions;
  20.  
  21. if (passwordOptions == null)
  22. {
  23. _passwordOptions = new PasswordOptions
  24. {
  25. RequiredLength = 8,
  26. RequiredUniqueChars = 4,
  27. RequireDigit = true,
  28. RequireLowercase = true,
  29. RequireNonAlphanumeric = true,
  30. RequireUppercase = true
  31. };
  32. }
  33. }
  34.  
  35. /// <summary>
  36. /// Генерирует случайный пароль.
  37. /// </summary>
  38. public string Next()
  39. {
  40. Span<char> chars = stackalloc char[_passwordOptions.RequiredLength];
  41.  
  42. if (_passwordOptions.RequireUppercase)
  43. {
  44. chars[_rand.Next(0, chars.Length)] = _randomChars[0][_rand.Next(0, _randomChars[0].Length)];
  45. }
  46.  
  47. if (_passwordOptions.RequireLowercase)
  48. {
  49. chars.Insert(_rand.Next(0, chars.Count),
  50. _randomChars[1][_rand.Next(0, _randomChars[1].Length)]);
  51. }
  52.  
  53. if (_passwordOptions.RequireDigit)
  54. {
  55. chars.Insert(_rand.Next(0, chars.Count),
  56. _randomChars[2][_rand.Next(0, _randomChars[2].Length)]);
  57. }
  58.  
  59. if (_passwordOptions.RequireNonAlphanumeric)
  60. {
  61. chars.Insert(_rand.Next(0, chars.Count),
  62. _randomChars[3][_rand.Next(0, _randomChars[3].Length)]);
  63. }
  64.  
  65. for (int i = chars.Count; i < _passwordOptions.RequiredLength
  66. || chars.Distinct().Count() < _passwordOptions.RequiredUniqueChars; i++)
  67. {
  68. string rcs = _randomChars[_rand.Next(0, _randomChars.Length)];
  69. chars.Insert(_rand.Next(0, chars.Count),
  70. rcs[_rand.Next(0, rcs.Length)]);
  71. }
  72.  
  73. return new string(chars.ToArray());
  74.  
  75. int DistinctCount(Span<char> charsSpan, int length)
  76. {
  77. int uniqueCount;
  78. Span<char> unique = stackalloc char[length];
  79.  
  80. foreach (char elem in charsSpan)
  81. {
  82.  
  83. }
  84. }
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement