Generating a random strong password
You can use the ASP.NET Membership provider to generate a new random strong password.
In the past I have usually either rolled my own authentication system or integrated an asp.net authentication system into an existing application and therefore I did not use the ASP.NET Membership system. In the current application I am writing, I had a need to generate a random strong password for the customer.
The ASP.NET Membership system already has a static method built-in for this. You can use the GeneratePassword static method from the Membership class to create a new password:
String strongPassword = System.Web.Security.Membership.GeneratePassword(8, 1);
From the MSDN documentation, the two parameters are:
- length – Int32
- The number of characters in the generated password. The length must be between 1 and 128 characters.
- numberOfNonAlphanumericCharacters – Int32
- The minimum number of punctuation characters in the generated password.
Also from the documentation: the generated password will contain alphanumeric characters and the following punctuation marks: !@#$%^&*()_-+=[{]};:<>|./?.
But also not included in the documentation is that the returned password will not be a “dangerous string”; in other words it won’t look like a block of script.
The Membership.GeneratePassword checks the newly generated password string using an internal method called CrossSiteScriptingValidation.IsDangerousString() and will not return a password that does not pass this test. It will just loop and continue to generate a new one until it is not considered a dangerous string. Pretty cool stuff!