0

I am looking to write a code to generate password using an input regex. I know we can validate a password against a regex but can we reverse engineer it and create a password ?

For example, if the regex is ^.*(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@!#$%^&*()+=]).*$ can we write a code in java to generate a random password that meets the requirement ? It should work for any regex.

Right now I have a very simple one. But I want to improve this

    // Method to generate a random alphanumeric password of a specific length
private static String generateRandomPassword(int len) {
    // ASCII range – alphanumeric (0-9, a-z, A-Z)
    final String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    SecureRandom random = new SecureRandom();
    return IntStream.range(0, len)
            .map(i -> random.nextInt(chars.length()))
            .mapToObj(randomIndex -> String.valueOf(chars.charAt(randomIndex)))
            .collect(Collectors.joining());
}
user229044
  • 232,980
  • 40
  • 330
  • 338
  • That's not what regex is for, so you probably shouldn't try to use it that way. Your regex also contains several `.*`'s which can produce an infinite amount of any kind of text, so it's not clear how you expect to generate strings to match this. The whole regular expression is very suspect, it certainly will not produce strong passwords, unless you hide a strong password in one of the `.*`'s. – user229044 Jun 28 '22 at 14:10
  • Well, I understand you point. However, I can have a length restriction. will that help ? The length restriction can be like ....anything between 7 to 12 chars for example – srinivas vishnu Jun 28 '22 at 14:22
  • You're still misusing regex for something it's not for. – user229044 Jun 28 '22 at 14:25

0 Answers0