:::: MENU ::::

Monday, November 9, 2009

The ASP.NET Membership system 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.