I am working on a personal .NET project (C# language) password generator based on the user’s inputs which will dictate the password complexity - including alphabetic, numeric, symbols/special characters, upper, lowercase and number of characters. Randomisation will based on a cryptographic algorithm - still have to decide which.
Is it possible to generate randomised characters from a regex (say [a-z], [A-Z, [0-9]) rather than having a string containing hard-coded alphabetic characters or numbers?
CodePudding user response:
Did you try googling this? There seems to be quite a few libraries that do exactly that. E.g. https://github.com/moodmosaic/Fare
CodePudding user response:
Yes, I wrote a snippet which does just that via a user pattern. It allows one to create a sequence of numbers and letters, or any character needed, in a sequence defined by the user. Here is the code
Random rn = new Random();
string charsToUse = "AzByCxDwEvFuGtHsIrJqKpLoMnNmOlPkQjRiShTgUfVeWdXcYbZa1234567890";
MatchEvaluator RandomChar = delegate (Match m)
{
return charsToUse[rn.Next( charsToUse.Length )].ToString();
};
Console.WriteLine( Regex.Replace( "XXXX-XXXX-XXXX-XXXX-XXXX", "X", RandomChar ) );
// Result: Lv2U-jHsa-TUep-NqKa-jlBx
Console.WriteLine( Regex.Replace( "XXXX", "X", RandomChar ) );
// Result: 8cPD
What is happening is that in the Regex.Replace
we specify a pattern by X
s. Anything which is not an X
is ignored and left in the result. We specify what characters to use in the string charsToUse and in this case we have A-Za-z0-9
expressed as written out. When we run the Regex.Replac
e it returns the pattern we specified with the characters we needed.
Copied from my blog C#: Generate a Random Sequence of Numbers and Letters From a User Defined Pattern and Characters