Secure random password generator for .NET Core

Recently, I was asked to replace the legacy and insecure password generator with the new one written in C#. After a minute of googling, I found pretty old .NET Membership function GeneratePassword from the namespace System.Web.Security. However, this package is not available in .NET Core. I also didn’t like any library or sample I managed to google out because of their design or security. So I spent a day crafting a secure random password generator for .NET Core.

Nuget package

Just install Raget.Security.Passwords nuget package and use it like this:

using Raget.Security.Passwords;
...
const int entropy = 128;          
using var generator = new DefaultPasswordGenerator();

var password = generator.GenerateAlphanumericPassword(entropy);

Under the hood, this library uses a system default secure random number generator. See .NET documentation.

To see more usages like custom character pool or custom random number generator usage, visit the project github page. The next paragraphs contain a little bit of theory about generated password strength.

Generated password strength

You are often forced to have at least one digit or upper case in your password. However, the only thing that matters in the case of a randomly generated password is its entropy. Entropy (in bits) is the base-2 logarithm of the total number of guesses needed to try all possibilities. To count entropy we will need the size of the character set (character pool size), password length, and the following formula:

H=\log _{2}N^{L}=L\log _{2}N=L{\log N \over \log 2}
Taken from https://en.wikipedia.org/wiki/Password_strength

Where H is entropy, N is a number of unique characters in a pool from which we randomly pick a character, and L is a password length.

To have a strong generated password you should aim for the entropy of at least 128 bits (in the time of writing). So you will get 39 characters long generated password if you choose only from Arabic numerals or 22 if you add also lower and upper case English letters.

Therefore, generate a random password and assuring that it has at least one digit, one upper-case character, or some special character, simply doesn’t make sense.

Leave a Reply

Your email address will not be published. Required fields are marked *