我目前正在尝试制作随机密码生成器 .
如果我只挑选一种符号,我的代码工作正常 .
使我的代码为多种类型的单词的最佳方法是什么?
您还会添加哪些参数以使密码更安全?
我正在考虑添加一个if循环来检查一行中是否有两个以上相同的字母,符号或数字 .
这就是我的界面的样子:
那是我的代码:
public partial class Form1 : Form
{
// Max number of identical characters in a row
const int Maximum_Identical = 2;
// lower case chars
const string lower_chars = "abcdefghijklmnopqrstuvwxyz";
// capital chars
const string capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// numbers
const string numbers = "0123456789";
// symbols
const string symbols = @"!#$%&*@\";
// password lenght
int lenght;
private void button1_Click(object sender, EventArgs e)
{
//use stringbuilder so I can add more chars later
StringBuilder password = new StringBuilder();
//take max lenght from numericUpDown
lenght = Convert.ToInt32(numericUpDown1.Value);
// random instance so I can use Next and don't get loops
Random rdm = new Random();
if (small_letters__Box.Checked)
{
//add a random small character to pass untill it reaches the selected lenght
while (lenght-- > 0 )
{
password.Append(lower_chars[rdm.Next(lower_chars.Length)]);
}
}
if (capital_letters__Box.Checked)
{
//add a random capital character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(capital_chars[rdm.Next(capital_chars.Length)]);
}
}
if (numbers_Box.Checked)
{
//add a random character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(numbers[rdm.Next(numbers.Length)]);
}
}
if (symbols_Box.Checked)
{
//add a random character to pass untill it reaches the selected lenght
while (lenght-- > 0)
{
password.Append(symbols[rdm.Next(symbols.Length)]);
}
}
textBox1.Text = password.ToString();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
}
}
6 回答
下面的代码是我已编写的代码,这是我几年前写的代码,我仍然在我需要的许多项目中使用它,它涵盖了你需要的所有内容
我喜欢你的主意 . 试试这段代码:
你去:
我为你写了这段代码 . 您可以复制并使用它 . 我的所有代码都只是一个可以传递适当参数的方法,它会为您提供完全随机化的密码 . 我在回答你的问题之前测试了几次,效果很好 .
使用完全随机化char并使用char的最大重复的答案,我添加了一个shuffle字符串函数:
随机字符串功能:
您的密码生成有两个步骤 .
确定字符集
从长度为n的字符集中随机创建密码
函数1创建字符集:
功能2从您的字符集创建给定长度的密码
然后,只需安装按钮单击事件处理程序即可调用这些函数并显示生成的密码 .