【发布时间】:2021-07-01 18:54:21
【问题描述】:
所以给定 5 位密码,破解密码的最大尝试次数应该是 62^5,但我得到的是 3 位数字 (62*5)。我应该改变什么?
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");
}
}
}
//Recursive Method
private static int cracking(int length, String password, String characters, int tries, String tryPass) {
System.out.println(length);
//Base case
if (length == 0) {
return 0;
}
//Recursive Base
for (int i = 0; i < characters.length(); i++) {
if (password.charAt(length-1) == characters.charAt(i)) {
tryPass = characters.charAt(i) + tryPass;
break;
}
tries++;
}
System.out.println("It took " + tries + " tries to crack the password");
cracking((length-1), password, characters, tries, tryPass);
return 0;
}
}
结果
按1生成随机密码
1
AFNTK
5
破解密码花了 36 次尝试
4
破解密码花了 81 次尝试
3
破解密码花了 120 次尝试
2
破解密码花了 125 次尝试
1
破解密码花了 151 次尝试
0
【问题讨论】:
标签: java recursion passwords combinations