所以代码运行正常,但是尝试破解5个字母的密码的次数是错误的。我试过修复一些东西,但是它总是给我3位数。尝试的次数应该高得多。下面是我的代码:
import java.util.Scanner;
import java.util.Random;
class Main {
public static void main(String[] args) {
// Letters for the random generated password
// Variables
String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
Random order = new Random();
int PASSWORD = letters.length();
// While statement to allow user to keep generating passwords
while (true) {
String password = "";
Scanner input = new Scanner(System.in);
// Print/menu
System.out.println("Press 1 to generate a random password");
// Takes user input
int UserOption = input.nextInt();
// If user input equals 1
if (UserOption == 1) {
// Generate a 5-character passwords from the letters in the String
for (int i = 0; i < 5; i++) {
password = password + letters.charAt(order.nextInt(PASSWORD));
}
System.out.println(password);
cracking(5, password, letters, 0, "");
}
// If user input is anything except 1
else {
// Print error
System.out.println("Error");
}
}
}
//Method for cracking password
private static int cracking(int length, String password, String characters, int tries, String tryPass) {
System.out.println(length);
if (length == 0) {
System.out.println("It took " + tries + " tries to crack the password");
return 0;
}
for (int i = 0; i < characters.length(); i++) {
if (password.charAt(length-1) == characters.charAt(i)) {
tryPass = tryPass + characters.charAt(i);
break;
}
tries++;
}
cracking((length-1), password, characters, tries, tryPass);
return 0;
}
}发布于 2021-04-05 14:12:39
您正在使用的字符集的长度为62。letters中的最后一个字符是0,因此匹配0所需的尝试次数是61尝试次数。
因此,即使随机生成的5个字母的密码包含00000 (所有字符都是字符集的最后一个字符),尝试的总次数也是61*5,即305。所以输出永远不会大于这个值。
因此,这段代码永远不会返回比3位数高得多的值。(我假设您期望的是4位或5位数字)。此外,它可以返回的最大值是305。
如果您需要更高的尝试次数,请增加密码长度。
https://stackoverflow.com/questions/66948564
复制相似问题