gpt4 book ai didi

c# - c#中的密码生成器

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:33 25 4
gpt4 key购买 nike

我想在我的 ASP.NET C# Web 应用程序中创建一个随 secret 码生成器。

我已经创建了它,但它仅适用于整数格式。如果我给出任何字符,它会将调试错误显示为“我的输入格式错误”。

但我想同时输入字符串和整数。例如我的文本框字段可能是

dft-001



我想要这个值的随 secret 码,而且我的长度应该限制为 8 位数字或字符。

我当前的代码:
public static string CreateRandomPassword(int PasswordLength)
{

string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789-";
Random randNum = new Random();
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;

for (int i = 0; i < PasswordLength; i++)
{
chars[i] = _allowedChars[(int)((_allowedChars.Length) * randNum.NextDouble())];
}

return new string(chars);
}


protected void Button1_Click(object sender, EventArgs e)
{
userid.Text = "Your id is: " + id.Text;
if(id .Text!="")
{

string myInt = id.Text.ToString();
password.Text = "Your password is: " + CreateRandomPassword(int.Parse(myInt));
}
}

最佳答案

根据您在要求中所述的内容,您可以采取一些措施来纠正此问题。

public static string CreateRandomPassword()  //If you are always going to want 8 characters then there is no need to pass a length argument
{
string _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789-";
Random randNum = new Random((int)DateTime.Now.Ticks); //Don't forget to seed your random, or else it won't really be random
char[] chars = new char[8];
//again, no need to pass this a variable if you always want 8

for (int i = 0; i < 8; i++)
{
chars[i] = _allowedChars[randNum.Next(_allowedChars.Length)];
//No need to over complicate this, passing an integer value to Random.Next will "Return a nonnegative random number less than the specified maximum."
}
return new string(chars);
}


protected void Button1_Click(object sender, EventArgs e)
{
userid.Text = "Your id is: " + id.Text;
if(id .Text!="")
{
password.Text = "Your password is: " + CreateRandomPassword();
}
}

如果我已经理解您想要正确执行的操作,那么这应该可以帮助您。

引用: MSDN Random.Next

关于c# - c#中的密码生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5269082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com