在 C# 中生成随机密码

这篇文章将讨论如何在 C# 中生成指定长度的加密强随机密码。

1.使用 Random Class

这个想法是从选定的 ASCII 字符范围中随机选择字符,并从中构造一个所需长度的字符串。

要构建随机字母数字密码,ASCII 范围应由数字、大写和小写字符组成,如下所示。我们可以进一步扩展以下代码以生成任何其他属于某个 ASCII 范围的字符。

2.使用 RNGCryptoServiceProvider Class

 RNGCryptoServiceProvider 类应该在 Random 类以确保加密强的随机数生成器。下面的代码示例使用 RNGCryptoServiceProvider 班级。

3.使用 Membership.GeneratePassword() 方法

要生成指定长度的随机密码,我们还可以使用 Membership.GeneratePassword() 方法从 System.Web.Security 命名空间。它采用生成密码中非字母数字字符的长度和最小数量。

其用法可见 这里.

示例代码如下:

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Web.Security" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
public void CreateUser_OnClick(object sender, EventArgs args)
{
  // Generate a new 12-character password with at least 1 non-alphanumeric character.
  string password = Membership.GeneratePassword(12, 1);
  try
  {
    // Create new user.
    MembershipUser newUser = Membership.CreateUser(UsernameTextbox.Text, password, 
                                                   EmailTextbox.Text);
    Msg.Text = "User <b>" + Server.HtmlEncode(UsernameTextbox.Text) + "</b> created. " +
               "Your temporary password is " + password + ".";
  }
  catch (MembershipCreateUserException e)
  {
    Msg.Text = GetErrorMessage(e.StatusCode);
  }
  catch (HttpException e)
  {
    Msg.Text = e.Message;
  }
}
public string GetErrorMessage(MembershipCreateStatus status)
{
   switch (status)
   {
      case MembershipCreateStatus.DuplicateUserName:
        return "Username already exists. Please enter a different user name.";
      case MembershipCreateStatus.DuplicateEmail:
        return "A username for that email address already exists. Please enter a different email address.";
      case MembershipCreateStatus.InvalidPassword:
        return "The password provided is invalid. Please enter a valid password value.";
      case MembershipCreateStatus.InvalidEmail:
        return "The email 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.";
      default:
        return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
   }
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Create User</title>
</head>
<body>
<form id="form1" runat="server">
  <h3>Create New User</h3>
  <asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />
  <table cellpadding="3" border="0">
    <tr>
      <td>Username:</td>
      <td><asp:Textbox id="UsernameTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <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>
    </tr>
    <tr>
      <td></td>
      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
    </tr>
  </table>
</form>
</body>
</html>