-
Notifications
You must be signed in to change notification settings - Fork 11
/
scilab code
98 lines (84 loc) · 2.99 KB
/
scilab code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace CsharpAcademy
{
public class PasswordGenerator
{
private enum CharType
{
Lowercase,
Uppercase,
Digit,
Special
}
public int Length { get; set; }
public int MinLowercases { get; set; }
public int MinUppercases { get; set; }
public int MinDigits { get; set; }
public int MinSpecials { get; set; }
private readonly Dictionary<CharType, string> _chars = new Dictionary<CharType, string>()
{
{ CharType.Lowercase, "abcdefghijklmnopqrstuvwxyz" },
{ CharType.Uppercase, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ CharType.Digit, "0123456789" },
{ CharType.Special, "!@#$%^&*()-_=+{}[]?<>.," }
};
private Dictionary<CharType, int> _outstandingChars = new Dictionary<CharType, int>();
public string Generate()
{
if (Length < MinLowercases + MinUppercases + MinDigits + MinSpecials)
{
throw new ArgumentException("Minimum requirements exceed password length.");
}
ResetOutstandings();
var password = new StringBuilder();
for (int i = 0; i < Length; i++)
{
if (_outstandingChars.Sum(x => x.Value) == Length - i)
{
var outstanding = _outstandingChars.Where(x => x.Value > 0).Select(x => x.Key).ToArray();
password.Append(DrawChar(outstanding));
}
else
{
password.Append(DrawChar());
}
}
return password.ToString();
}
private void ResetOutstandings()
{
_outstandingChars[CharType.Lowercase] = MinLowercases;
_outstandingChars[CharType.Uppercase] = MinUppercases;
_outstandingChars[CharType.Digit] = MinDigits;
_outstandingChars[CharType.Special] = MinSpecials;
}
private char DrawChar(params CharType[] types)
{
var filteredChars = types.Length == 0 ? _chars : _chars.Where(x => types.Contains(x.Key));
int length = filteredChars.Sum(x => x.Value.Length);
int index = RandomNumberGenerator.GetInt32(length);
int offset = 0;
foreach (var item in filteredChars)
{
if (index < offset + item.Value.Length)
{
DecreaseOustanding(item.Key);
return item.Value[index - offset];
}
offset += item.Value.Length;
}
return new char();
}
private void DecreaseOustanding(CharType type)
{
if (_outstandingChars[type] > 0)
{
_outstandingChars[type]--;
}
}
}
}