Java/src/main/java/Main.java
Emma Nora Theuer e400ac1254 Initial Commit
2024-09-04 18:47:29 +02:00

95 lines
3.4 KiB
Java

import java.security.SecureRandom;
import java.io.IOException;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.List;
import picocli.CommandLine;
import picocli.CommandLine.Option;
public class Main implements Runnable {
private static SecureRandom random;
@Option(names = {"-x", "--xkcd"}, description = "Will generate an xkcd-style password (See xkcd 936)")
private boolean xkcd = false;
@Option(names = {"-s", "--simple"}, description = "Will generate a password of specified length without special characters")
private boolean simple = false;
@Option(names = {"-l", "--length"}, description = "Will generate a regular password with the provided amount of characters (or words for XKCD passwords). Defaults to 32.")
private int length = 32;
@Option(names = {"-h", "--help"}, usageHelp = true, description = "Displays this help message and exits.")
private boolean help;
private static String generate_simple_password(int count) {
String simpleCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
String password = "";
int randomIndex;
char randomChar;
for (int i = 0; i < count; i++) {
randomIndex = random.nextInt(simpleCharacters.length());
randomChar = simpleCharacters.charAt(randomIndex);
password = password + randomChar;
}
return password;
}
private static String generate_regular_password(int count) {
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*";
String password = "";
int randomIndex;
char randomChar;
for (int i = 0; i < count; i++) {
randomIndex = random.nextInt(characters.length());
randomChar = characters.charAt(randomIndex);
password = password + randomChar;
}
return password;
}
private static String generate_xkcd_password(int count) {
String password = "";
try {
List<String> dictionary = Files.readAllLines(Paths.get("/usr/share/dict/words"));
int randomIndex;
String randomWord;
for (int i = 0; i < count; i++) {
randomIndex = random.nextInt(dictionary.size());
randomWord = dictionary.get(randomIndex);
password = password + randomWord;
password = password + " ";
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("An error occured while reading /usr/share/dict/words - Is the file present?");
System.exit(2);
}
return password;
}
public static void main(String[] args) {
random = new SecureRandom();
int exitCode = new CommandLine(new Main()).execute(args);
System.exit(exitCode);
}
@Override
public void run() {
if (xkcd && simple) {
System.out.println("Error: Only use one of xkcd (-x), simple (-s) or regular (-r) at once.");
System.exit(2);
}
if (xkcd) {
System.out.println(generate_xkcd_password(length));
System.exit(0);
}
else if (simple) {
System.out.println(generate_simple_password(length));
System.exit(0);
}
else {
System.out.println(generate_regular_password(length));
System.exit(0);
}
}
}