Generate a Secure Random Password in Java with Minimum Special Character Requirements

后端 未结 4 1913
暖寄归人
暖寄归人 2021-02-04 10:35

How do I create a random password that meets the system\'s length and character set requirements in Java?

I have to create a random password that is 10-14 characters lo

4条回答
  •  时光说笑
    2021-02-04 11:11

    Here is a utility that uses just vanilla Java and implements the requirements. It basically gets one of each of the required character sets. Then populates the rest with random chars from the whole set. Then shuffles it all up.

    public class PasswordUtils {
    
        static char[] SYMBOLS = (new String("^$*.[]{}()?-\"!@#%&/\\,><':;|_~`")).toCharArray();
        static char[] LOWERCASE = (new String("abcdefghijklmnopqrstuvwxyz")).toCharArray();
        static char[] UPPERCASE = (new String("ABCDEFGHIJKLMNOPQRSTUVWXYZ")).toCharArray();
        static char[] NUMBERS = (new String("0123456789")).toCharArray();
        static char[] ALL_CHARS = (new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789^$*.[]{}()?-\"!@#%&/\\,><':;|_~`")).toCharArray();
        static Random rand = new SecureRandom();
    
        public static String getPassword(int length) {
            assert length >= 4;
            char[] password = new char[length];
    
            //get the requirements out of the way
            password[0] = LOWERCASE[rand.nextInt(LOWERCASE.length)];
            password[1] = UPPERCASE[rand.nextInt(UPPERCASE.length)];
            password[2] = NUMBERS[rand.nextInt(NUMBERS.length)];
            password[3] = SYMBOLS[rand.nextInt(SYMBOLS.length)];
    
            //populate rest of the password with random chars
            for (int i = 4; i < length; i++) {
                password[i] = ALL_CHARS[rand.nextInt(ALL_CHARS.length)];
            }
    
            //shuffle it up
            for (int i = 0; i < password.length; i++) {
                int randomPosition = rand.nextInt(password.length);
                char temp = password[i];
                password[i] = password[randomPosition];
                password[randomPosition] = temp;
            }
    
            return new String(password);
        }
    
        public static void main(String[] args) {
            for (int i = 0; i < 100; i++) {
                System.out.println(getPassword(8));
            }
        }
    }
    

提交回复
热议问题