gpt4 book ai didi

java - 随 secret 码生成

转载 作者:行者123 更新时间:2023-11-30 06:26:19 24 4
gpt4 key购买 nike

我写了一个随 secret 码生成的代码。有一个字符串,我必须从中创建密码。所以我尝试根据大写数组、小写数组和数字数组对字符串进行分类。但是问题来了..

         for(int k=0;k<Length;k++){
if(asc[k]>=65 && asc[k]<=90){
UpperCase[k]=(char)asc[k];
}
else if(asc[k]>=48 && asc[k]<=57){
Digit[k]=(char)asc[k];
}
else {
Mixed[k]=(char)asc[k];
}
}

被执行它计算了一些我不想要的空间。编码看起来像丑陋的 sry 因为我糟糕的编码。我知道有更多的方法来解决它但我想通过这个。这是我的代码。这是我的代码

import java.util.Random;

public class Randompassgeneration
{

final int MAX_LENGTH = 20;
final int MIN_LENGTH = 3;

char[] password=new char[25];
int [] asc=new int[18];
char[] UpperCase=new char[25];
char[] Digit=new char[25];
char[] Mixed=new char[25];
public void generate(String allowedCharacters)
{
int Length=allowedCharacters.length();


for (int i=0;i<Length;i++)
{
asc[i]=(int)allowedCharacters.charAt(i);

}
for (int k=0;k<Length;k++)
{
if (asc[k]>=65 && asc[k]<=90)
{
UpperCase[k]=(char)asc[k];
}
else if (asc[k]>=48 && asc[k]<=57)
{
Digit[k]=(char)asc[k];
}
else
{
Mixed[k]=(char)asc[k];
}
}

String rp=null;
StringBuilder Strbld=new StringBuilder();
Random rnd=new Random();
int ranStrLen=rnd.nextInt(MAX_LENGTH - MIN_LENGTH + 1) + MIN_LENGTH;
Strbld.append(UpperCase[rnd.nextInt(UpperCase.length)]);
Strbld.append(Digit[rnd.nextInt(Digit.length)]);

for (int m=0; m<ranStrLen-2; m++)
{
Strbld.append(Mixed[rnd.nextInt(Mixed.length)]);

}

System.out.print(ranStrLen +"->"+ Strbld.toString());


}

public static void main(String[] args)
{
String allowedCharacters = "weakPasSWorD1234$*";
Randompassgeneration t=new Randompassgeneration();
t.generate(allowedCharacters);
}
}

有什么建议吗?

最佳答案

我会生成最少数量的字符、数字和符号。随机填充其他字符并将结果洗牌。这样,它将以最少的努力满足您的最低要求。

public static String passwordGenerator() {
List<Character> chars = new ArrayList<>();
Random rand = new Random();
// min number of digits
for (int i = 0; i < 1; i++) chars.add((char) ('0' + rand.nextInt(10)));
// min number of lower case
for (int i = 0; i < 2; i++) chars.add((char) ('a' + rand.nextInt(26)));
// min number of upper case
for (int i = 0; i < 1; i++) chars.add((char) ('A' + rand.nextInt(26)));
// min number of symbols
String symbols = "!\"$%^&*()_+{}:@~<>?,./;'#][=-\\|'";
for (int i = 0; i < 1; i++) chars.add(symbols.charAt(rand.nextInt(symbols.length())));
// fill in the rest
while (chars.size() < 8) chars.add((char) ('!' + rand.nextInt(93)));
// appear in a random order
Collections.shuffle(chars);
// turn into a String
char[] arr = new char[chars.size()];
for (int i = 0; i < chars.size(); i++) arr[i] = chars.get(i);
return new String(arr);
}

public static void main(String... args) {
for (int i = 0; i < 100; i++)
System.out.println(passwordGenerator());
}

关于java - 随 secret 码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459035/

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