question

JassimAlRahma-9056 avatar image
0 Votes"
JassimAlRahma-9056 asked WenyanZhang-MSFT edited

Generate Random Password based on Regex Pattern

Hi,

I have below Regex for my password:

 internal const string PasswordRegex = @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$";

How can i generate random passwords which match the above pattern?


Thanks,
Jassim


dotnet-csharpdotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered

If not opposed to a non regular expression generator, see the following NuGet package, source code, test. The package has over 500.000 downloads and meets OWASP requirements.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

WenyanZhang-MSFT avatar image
0 Votes"
WenyanZhang-MSFT answered WenyanZhang-MSFT edited

Hello,
Welcome to our Microsoft Q&A platform!
You can get the random passwords like following code:

 string chars = "0123456789ABCDEFGHIJKLMNOPQSTUVWXYZabcdefghijklmnpqrstuvwxyz";
 private string creat()
 {
 Random randomNnmber = new Random();
 int len = randomNnmber.Next(8, 15);//get the max(15) and min(8)
 string randomStr = "";
    
 for (int i = 0; i < len; i++)
 {
 randomStr += chars[randomNnmber.Next(chars.Length)];
 }
 if (!Regex.IsMatch(randomStr, PasswordRegex))// the PasswordRegex you provided
 {
 Console.WriteLine($"{randomStr}");
 return creat();
 }
 else
 {
 Console.WriteLine($"{randomStr}");
 return randomStr;
 }
 }


Best Regards,

Wenyan Zhang



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.