NCode.PasswordGenerator 2.1.1

Prefix Reserved
dotnet add package NCode.PasswordGenerator --version 2.1.1
                    
NuGet\Install-Package NCode.PasswordGenerator -Version 2.1.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="NCode.PasswordGenerator" Version="2.1.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NCode.PasswordGenerator" Version="2.1.1" />
                    
Directory.Packages.props
<PackageReference Include="NCode.PasswordGenerator" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NCode.PasswordGenerator --version 2.1.1
                    
#r "nuget: NCode.PasswordGenerator, 2.1.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package NCode.PasswordGenerator@2.1.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NCode.PasswordGenerator&version=2.1.1
                    
Install as a Cake Addin
#tool nuget:?package=NCode.PasswordGenerator&version=2.1.1
                    
Install as a Cake Tool

NCode.PasswordGenerator

CI Target framework License

NuGet

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.AmbiguousCharacters lists the characters that look alike.
  • A password is returned only after PasswordGeneratorOptions.IsValid accepts it. The generator retries up to MaxAttempts times.
  • Output as a string, into your own Span<char>, or into a pinned buffer that is zeroed when you dispose it.
  • AddPasswordGenerator registers 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;
  • MinLength is below 1;
  • MinLength is greater than MaxLength;
  • the minimum counts add up to more than MaxLength;
  • MaxAttempts or MaxConsecutiveIdenticalCharacters is below 1;
  • a class has a minimum above 0 and no character is left after the exclusions.

SetLengthRange and EstimateEntropyBits throw ArgumentOutOfRangeException when:

  • SetLengthRange gets a minimum above its maximum;
  • EstimateEntropyBits gets a negative length.

Generate and GeneratePinned throw InvalidOperationException when:

  • MinLength is greater than MaxLength;
  • the length is outside the range from MinLength to MaxLength, or is 0 or less;
  • every minimum count is 0;
  • the minimum counts don't fit the length;
  • no valid password is found in MaxAttempts tries (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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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.

Version Downloads Last Updated
2.1.1 12 11/30/2026
2.1.0 63 11/29/2026
2.0.0 99 11/28/2026
1.0.1 5,753 7/16/2023
1.0.0 2,891 7/16/2023