NCode.PasswordGenerator
2.1.0
Prefix Reserved
See the version list below for details.
dotnet add package NCode.PasswordGenerator --version 2.1.0
NuGet\Install-Package NCode.PasswordGenerator -Version 2.1.0
<PackageReference Include="NCode.PasswordGenerator" Version="2.1.0" />
<PackageVersion Include="NCode.PasswordGenerator" Version="2.1.0" />
<PackageReference Include="NCode.PasswordGenerator" />
paket add NCode.PasswordGenerator --version 2.1.0
#r "nuget: NCode.PasswordGenerator, 2.1.0"
#:package NCode.PasswordGenerator@2.1.0
#addin nuget:?package=NCode.PasswordGenerator&version=2.1.0
#tool nuget:?package=NCode.PasswordGenerator&version=2.1.0
NCode.PasswordGenerator
NCode.PasswordGenerator is a .NET library that generates cryptographically random passwords that meet configurable rules. You can use it with dependency injection or on its own.
Features
- Every random choice (length, characters and order) comes from
System.Security.Cryptography.RandomNumberGenerator. - Rules for a length range, minimum counts of lowercase, uppercase, numeric and special characters, a custom set of
special characters, the longest run of identical characters, and characters to exclude.
PasswordGeneratorOptions.AmbiguousCharacterslists the characters that look alike. - A password is returned only after
PasswordGeneratorOptions.IsValidaccepts it. The generator retries up toMaxAttemptstimes. - Output as a
string, into your ownSpan<char>, or into a pinned buffer that is zeroed when you dispose it. AddPasswordGeneratorregisters the generator with dependency injection, and the options are validated when the host starts.- An estimate of a password's entropy in bits.
- Trim-compatible and Native AOT-compatible.
Requirements
.NET 10 or later. The package targets net10.0. Version 1.x targets .NET Standard 2.1, for apps on older runtimes.
Installation
dotnet add package NCode.PasswordGenerator
Getting started
using NCode.PasswordGenerator;
string password = PasswordGenerator.Default.Generate();
The defaults give a password of 16 to 64 characters with at least one lowercase, one uppercase, one numeric and one special character, and at most 2 identical characters in a row.
Dependency injection
Register the generator with AddPasswordGenerator, and pass a callback to set the options:
using NCode.PasswordGenerator;
builder.Services.AddPasswordGenerator(options => options
.SetLengthRange(20, 32)
.SetMinSpecialCharacters(2)
.SetExcludedCharacters(PasswordGeneratorOptions.AmbiguousCharacters));
public class AccountService(IPasswordGenerator passwordGenerator)
{
public string CreateTemporaryPassword() => passwordGenerator.Generate();
}
AddPasswordGenerator() without arguments uses the defaults. It registers PasswordGenerator as the singleton
IPasswordGenerator, and leaves an IPasswordGenerator that you registered earlier in place.
The options are validated when the host starts (ValidateOnStart), and when IOptions<PasswordGeneratorOptions> is
first read, as in an app without a host. Options that can't generate a password throw OptionsValidationException,
which lists every problem. The rules are under "Validation and errors" below.
Binding from configuration
To read the options from configuration, register the generator and bind a configuration section:
builder.Services.AddPasswordGenerator();
builder.Services.Configure<PasswordGeneratorOptions>(builder.Configuration.GetSection("PasswordGenerator"));
{
"PasswordGenerator": {
"MinLength": 20,
"MaxLength": 32,
"MinSpecialCharacters": 2,
"ExcludedCharacters": "0O1Il|"
}
}
Configure with an IConfiguration comes from Microsoft.Extensions.Options.ConfigurationExtensions, which
ASP.NET Core and the .NET Generic Host already reference.
The MinLength and MaxLength setters accept any value, so a section can set any range, such as a MinLength of 80
and a MaxLength of 100, whatever the order of its keys. AddPasswordGenerator checks the pair when the host starts.
Generating passwords
A generator is safe to share across threads. Don't change an options instance while a generator uses it.
The samples below use a generator variable of type IPasswordGenerator, such as PasswordGenerator.Default or an
instance from dependency injection.
Strings
Generate() uses the generator's own options. The length of the string is drawn at random from MinLength to
MaxLength, both included:
string password = generator.Generate();
To change the rules for one call, pass a callback. The callback applies to a copy of the generator's options, so the generator's own options stay unchanged:
string password = generator.Generate(options => options.SetExactLength(32));
You can also pass a PasswordGeneratorOptions instance:
var options = new PasswordGeneratorOptions()
.SetExactLength(24)
.SetMinNumericCharacters(3);
string password = generator.Generate(options);
Without dependency injection, new PasswordGenerator(options) makes a generator whose own options are options:
var generator = new PasswordGenerator(options);
Into a span
To keep a password out of a string, generate it into your own Span<char>:
Span<char> buffer = stackalloc char[20];
generator.Generate(buffer);
The password fills the whole span. The length of the span is the length of the password, and it must be from MinLength
to MaxLength, or the method throws InvalidOperationException. When no valid password is found, the method clears
the span before it throws.
Pinned buffers
GeneratePinned() returns the password in a buffer that you dispose when you finish with it:
using System.Buffers;
using IMemoryOwner<char> owner = generator.GeneratePinned();
ReadOnlySpan<char> password = owner.Memory.Span;
The buffer is on the pinned object heap, so the garbage collector never copies it, and disposing the owner zeroes it.
Memory throws ObjectDisposedException after you dispose the owner. The overloads take nothing, a callback, or
options, like Generate. An IPasswordGenerator that is implemented outside the library throws
NotSupportedException from them unless it overrides them.
Many passwords
A generator is also an IEnumerable<string>, so you can use LINQ to take several passwords:
using System.Linq;
List<string> passwords = generator.Take(5).ToList();
Enumerating a generator yields at most MaxEnumerations passwords (100 by default), each with the generator's own
options.
Options
PasswordGeneratorOptions holds the rules. Every setter returns the options, so calls chain.
| Property | Setter | Default | Rule |
|---|---|---|---|
MinLength |
SetMinLength |
16 |
The shortest password. |
MaxLength |
SetMaxLength |
64 |
The longest password. |
ExactLength (set only) |
SetExactLength |
none | Sets both length bounds to one value. |
MinLowercaseCharacters |
SetMinLowercaseCharacters |
1 |
The fewest lowercase characters. |
MinUppercaseCharacters |
SetMinUppercaseCharacters |
1 |
The fewest uppercase characters. |
MinNumericCharacters |
SetMinNumericCharacters |
1 |
The fewest numeric characters. |
MinSpecialCharacters |
SetMinSpecialCharacters |
1 |
The fewest special characters. |
SpecialCharacters |
SetSpecialCharacters |
listed below | The characters that count as special. |
ExcludedCharacters |
SetExcludedCharacters |
empty | Characters that never appear in a password. |
MaxConsecutiveIdenticalCharacters |
SetMaxConsecutiveIdenticalCharacters |
2 |
The longest run of one character. |
MaxAttempts |
SetMaxAttempts |
10000 |
The tries before the generator gives up. |
MaxEnumerations |
SetMaxEnumerations |
100 |
The passwords an enumeration yields. |
SetLengthRange(min, max) sets both bounds at once. Reset() restores the defaults, and Clone() copies the options.
CharacterSet is every character that a password can contain. IsValid(password) checks a password against the rules,
and rejects one that holds an excluded character.
Character sets
The lowercase characters are a to z, the uppercase characters are A to Z, and the numeric characters are 0 to
9. The default special characters are these 29:
!#$%&()*+,-./:;<=>?@[]^_`{|}~
PasswordGeneratorOptions.AmbiguousCharacters lists the characters that look alike:
0O1Il|
A class whose minimum is 0 is left out of CharacterSet. Excluded characters are removed from every class.
Validation and errors
AddPasswordGenerator rejects options with OptionsValidationException when:
- every minimum count is 0;
MinLengthis below 1;MinLengthis greater thanMaxLength;- the minimum counts add up to more than
MaxLength; MaxAttemptsorMaxConsecutiveIdenticalCharactersis below 1;- a class has a minimum above 0 and no character is left after the exclusions.
SetLengthRange and EstimateEntropyBits throw ArgumentOutOfRangeException when:
SetLengthRangegets a minimum above its maximum;EstimateEntropyBitsgets a negative length.
Generate and GeneratePinned throw InvalidOperationException when:
MinLengthis greater thanMaxLength;- the length is outside the range from
MinLengthtoMaxLength, or is 0 or less; - every minimum count is 0;
- the minimum counts don't fit the length;
- no valid password is found in
MaxAttemptstries (the message is "Too many attempts.").
They throw ArgumentException when a class with a minimum above 0 has no character left. This happens only for options
that AddPasswordGenerator didn't validate.
Password strength
EstimateEntropyBits(length) returns the length times the base 2 logarithm of the number of distinct characters in
CharacterSet. The result is an upper bound, because the minimum counts and the limit on identical characters in a row
narrow the choices.
double defaults = new PasswordGeneratorOptions().EstimateEntropyBits(16);
// about 104 bits: 16 characters from a set of 91
double unambiguous = new PasswordGeneratorOptions()
.SetExcludedCharacters(PasswordGeneratorOptions.AmbiguousCharacters)
.EstimateEntropyBits(16);
// about 103 bits: 16 characters from a set of 85
Learn more
License
NCode.PasswordGenerator is licensed under the Apache License 2.0.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 11.0.0)
- Microsoft.Extensions.Options (>= 11.0.0)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on NCode.PasswordGenerator:
| Package | Downloads |
|---|---|
|
NCode.Identity.Server
Package Description |
|
|
NCode.Identity.OpenId.Core
Package Description |
GitHub repositories
This package is not used by any popular GitHub repositories.
See the changelog: https://github.com/NCodeGroup/PasswordGenerator/blob/HEAD/CHANGELOG.md