csharp 如何生成具有规则的随机密码的示例。从计算机编程基础知识到C#http://www.introprogramming.i

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 如何生成具有规则的随机密码的示例。从计算机编程基础知识到C#http://www.introprogramming.i相关的知识,希望对你有一定的参考价值。

class RandomPasswordGenerator
{
  private const string CapitalLetters =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  private const string SmallLetters = 
  "abcdefghijklmnopqrstuvwxyz";
  private const string Digits = "0123456789";
  private const string SpecialChars = 
  "~!@#$%^&*()_+=`{}[]\\|':;.,/?<>";
  private const string AllChars =
  CapitalLetters + SmallLetters + Digits + SpecialChars;
  
  private static Random rnd = new Random();

  static void Main()
  {
    StringBuilder password = new StringBuilder();
    
    // Generate two random capital letters
    for (int i = 1; i <= 2; i++)
    {
      char capitalLetter = GenerateChar(CapitalLetters);
      InsertAtRandomPosition(password, capitalLetter);
    }
    
    // Generate two random small letters
    for (int i = 1; i <= 2; i++)
    {
      char smallLetter = GenerateChar(SmallLetters);
      InsertAtRandomPosition(password, smallLetter);
    }

    // Generate one random digit
    char digit = GenerateChar(Digits);
    InsertAtRandomPosition(password, digit);
    
    // Generate 3 special characters
    for (int i = 1; i <= 3; i++)
    {
      char specialChar = GenerateChar(SpecialChars);
      InsertAtRandomPosition(password, specialChar);
    }
    
    // Generate few random characters (between 0 and 7)
    int count = rnd.Next(8);
    for (int i = 1; i <= count; i++)
    {
      char specialChar = GenerateChar(AllChars);
      InsertAtRandomPosition(password, specialChar);
    }
    
    Console.WriteLine(password);
  }

  private static void InsertAtRandomPosition(
  StringBuilder password, char character)
  {
    int randomPosition = rnd.Next(password.Length + 1);
    password.Insert(randomPosition, character);
  }

  private static char GenerateChar(string availableChars)
  {
    int randomIndex = rnd.Next(availableChars.Length);
    char randomChar = availableChars[randomIndex];
    return randomChar;
  }
}

//  T2/F_b~|Hq

以上是关于csharp 如何生成具有规则的随机密码的示例。从计算机编程基础知识到C#http://www.introprogramming.i的主要内容,如果未能解决你的问题,请参考以下文章

csharp 随机密码生成器

csharp 随机密码生成器

csharp 如何使用Random类中的.Next()方法打印随机数序列的示例。从计算机程序基础

csharp 如何使用Random类中的.Next()方法打印随机数序列的示例。从计算机程序基础

如何生成具有不同边际分布的多元随机数?

csharp 如何在多维数组中找到具有最高和的大小为2乘2的子矩阵的示例。从计算机程序基础