Export (0) Print
Expand All

Membership.GeneratePassword Method

Generates a random password of the specified length.

Namespace:  System.Web.Security
Assembly:  System.Web (in System.Web.dll)

Public Shared Function GeneratePassword ( _
	length As Integer, _
	numberOfNonAlphanumericCharacters As Integer _
) As String


Type: System.Int32
The number of characters in the generated password. The length must be between 1 and 128 characters.
Type: System.Int32
The minimum number of non-alphanumeric characters (such as @, #, !, %, &, and so on) in the generated password.

Return Value

Type: System.String
A random password of the specified length.


length is less than 1 or greater than 128 -or-

numberOfNonAlphanumericCharacters is less than 0 or greater than length.

The GeneratePassword method is used to generate a random password and is most commonly used by the ResetPassword method implemented by a membership provider to reset the password for a user to a new, temporary password.

The generated password only contains alphanumeric characters and the following punctuation marks: !@#$%^&*()_-+=[{]};:<>|./?. No hidden or non-printable control characters are included in the generated password.


The random password created by the GeneratePassword method is not guaranteed to pass the regular expression in the PasswordStrengthRegularExpression property. However, the random password will meet the criteria established by the MinRequiredPasswordLength property and the numberOfNonAlphanumericCharacters parameter.

The following code example creates a new membership user and uses the GeneratePassword method to initialize the password for the new user to a random value, which is displayed to the user.

Security noteSecurity Note

This example contains a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Web.Security" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<script runat="server">

Public Sub CreateUser_OnClick(sender As Object, args As EventArgs)
  ' Create a new 12-character password with 1 non-alphanumeric character.
  Dim password As String = Membership.GeneratePassword(12, 1)

    ' Create new user.

    Dim newUser As MembershipUser = Membership.CreateUser(UsernameTextbox.Text, password, _

    Msg.Text = "User <b>" & Server.HtmlEncode(UsernameTextbox.Text) & "</b> created. " & _
               "Your temporary password is " & password & "."

  Catch e As MembershipCreateUserException
    Msg.Text = GetErrorMessage(e.StatusCode)
  Catch e As HttpException
    Msg.Text = e.Message
  End Try
End Sub

Public Function GetErrorMessage(status As MembershipCreateStatus) As String

   Select Case status
      Case MembershipCreateStatus.DuplicateUserName
        Return "Username already exists. Please enter a different user name."

      Case MembershipCreateStatus.DuplicateEmail
        Return "A username for that e-mail address already exists. Please enter a different e-mail address."

      Case MembershipCreateStatus.InvalidPassword
        Return "The password provided is invalid. Please enter a valid password value."

      Case MembershipCreateStatus.InvalidEmail
        Return "The e-mail address provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.InvalidAnswer
        Return "The password retrieval answer provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.InvalidQuestion
        Return "The password retrieval question provided is invalid. Please check the value and try again."

      Case MembershipCreateStatus.ProviderError
        Return "The authentication provider Returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."

      Case MembershipCreateStatus.UserRejected
        Return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."

      Case Else
        Return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."
   End Select
End Function


<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Create User</title>

<form id="form1" runat="server">
  <h3>Create New User</h3>

  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />

  <table cellpadding="3" border="0">
      <td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>

      <td>Email Address:</td>
      <td><asp:Textbox id="EmailTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
                                      ControlToValidate="EmailTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>

      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

© 2014 Microsoft