| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | |
| | | 4 | | namespace LOCKnet.Core.Services; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Standardimplementierung fuer <see cref="IPasswordGeneratorService"/>. |
| | | 8 | | /// </summary> |
| | | 9 | | public sealed class PasswordGeneratorService : IPasswordGeneratorService |
| | | 10 | | { |
| | | 11 | | private const string UppercaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
| | | 12 | | private const string LowercaseChars = "abcdefghijklmnopqrstuvwxyz"; |
| | | 13 | | private const string DigitChars = "0123456789"; |
| | | 14 | | private const string SpecialChars = "!@#$%^&*()-_=+[]{}|;:,.<>?/"; |
| | | 15 | | |
| | | 16 | | /// <inheritdoc/> |
| | | 17 | | public string Generate(PasswordGeneratorOptions options) |
| | 13 | 18 | | { |
| | 13 | 19 | | ArgumentNullException.ThrowIfNull(options); |
| | | 20 | | |
| | 12 | 21 | | var length = options.Length > 0 ? options.Length : 16; |
| | 12 | 22 | | var charsetBuilder = new StringBuilder(); |
| | | 23 | | |
| | 12 | 24 | | if (options.UseUppercase) |
| | 9 | 25 | | { |
| | 9 | 26 | | charsetBuilder.Append(UppercaseChars); |
| | 9 | 27 | | } |
| | | 28 | | |
| | 12 | 29 | | if (options.UseLowercase) |
| | 9 | 30 | | { |
| | 9 | 31 | | charsetBuilder.Append(LowercaseChars); |
| | 9 | 32 | | } |
| | | 33 | | |
| | 12 | 34 | | if (options.UseDigits) |
| | 10 | 35 | | { |
| | 10 | 36 | | charsetBuilder.Append(DigitChars); |
| | 10 | 37 | | } |
| | | 38 | | |
| | 12 | 39 | | if (options.UseSpecial) |
| | 10 | 40 | | { |
| | 10 | 41 | | charsetBuilder.Append(SpecialChars); |
| | 10 | 42 | | } |
| | | 43 | | |
| | 12 | 44 | | if (charsetBuilder.Length == 0) |
| | 1 | 45 | | { |
| | 1 | 46 | | charsetBuilder.Append(LowercaseChars); |
| | 1 | 47 | | } |
| | | 48 | | |
| | 12 | 49 | | var charset = charsetBuilder.ToString(); |
| | 12 | 50 | | var randomBytes = RandomNumberGenerator.GetBytes(length); |
| | 12 | 51 | | var password = new char[length]; |
| | | 52 | | |
| | 842 | 53 | | for (var i = 0; i < length; i++) |
| | 409 | 54 | | { |
| | 409 | 55 | | password[i] = charset[randomBytes[i] % charset.Length]; |
| | 409 | 56 | | } |
| | | 57 | | |
| | 12 | 58 | | return new string(password); |
| | 12 | 59 | | } |
| | | 60 | | } |