"景先生毕设|www.jxszl.com

C#创建给定长度的随机密码

2023-09-12 15:40编辑: www.jxszl.com景先生毕设
                      C#创建给定长度的随机密码

使用大写、小写、数字和特殊字符创建随机密码/数字的代码。
.Net提供了类随机,它有三种方法:Next、NextBytes和NextDouble。
Next():Next方法返回一个随机数。
NextBytes():NextBytes返回一个由随机数字填充的字节数组。
NextDouble():在0.0和1.0之间返回一个随机数。

////
//
///
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
namespace PasswordPractice {  
    class PasswordCreate {  
        //函数是随机输入密码
        public string makeRandomPassword(int length) {  
            string UpperCase = "QWERTYUIOPASDFGHJKLZXCVBNM";  
            string LowerCase = "qwertyuiopasdfghjklzxcvbnm";  
            string Digits = "1234567890";  
            string allCharacters = UpperCase + LowerCase + Digits;  
            //随机将给出给定长度的随机字符
            Random r = new Random();  
            String password = "";  
            for (int i = 0; i < length; i++) {  
                double rand = r.NextDouble();  
                if (i == 0) {  
                    password += UpperCase.ToCharArray()[(int) Math.Floor(rand * UpperCase.Length)];  
                } else {  
                    password += allCharacters.ToCharArray()[(int) Math.Floor(rand * allCharacters.Length)];  
                }  
            }  
            Console.WriteLine(password);  
            Console.ReadLine();  
            return password;  
        }  
        static void Main(string[] args) {  
            // Input  
            Console.WriteLine("输入密码的长度");  
            string len = Console.ReadLine();  
            PasswordCreate n = new PasswordCreate();  
            //在main方法中调用方法
            n.makeRandomPassword(Convert.ToInt32(len));  
        }  
    }  
}
原文链接:http://www.jxszl.com/biancheng/C/445952.html