java generate secure random password

Solutions on MaxInterview for java generate secure random password by the best coders in the world

showing results for - "java generate secure random password"
Marc
07 Apr 2018
1public class PasswordUtils {
2
3    static char[] SYMBOLS = "^$*.[]{}()?-\"!@#%&/\\,><':;|_~`".toCharArray();
4    static char[] LOWERCASE = "abcdefghijklmnopqrstuvwxyz".toCharArray();
5    static char[] UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
6    static char[] NUMBERS = "0123456789".toCharArray();
7    static char[] ALL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789^$*.[]{}()?-\"!@#%&/\\,><':;|_~`".toCharArray();
8    static Random rand = new SecureRandom();
9
10    public static String getPassword(int length) {
11        assert length >= 4;
12        char[] password = new char[length];
13
14        //get the requirements out of the way
15        password[0] = LOWERCASE[rand.nextInt(LOWERCASE.length)];
16        password[1] = UPPERCASE[rand.nextInt(UPPERCASE.length)];
17        password[2] = NUMBERS[rand.nextInt(NUMBERS.length)];
18        password[3] = SYMBOLS[rand.nextInt(SYMBOLS.length)];
19
20        //populate rest of the password with random chars
21        for (int i = 4; i < length; i++) {
22            password[i] = ALL_CHARS[rand.nextInt(ALL_CHARS.length)];
23        }
24
25        //shuffle it up
26        for (int i = 0; i < password.length; i++) {
27            int randomPosition = rand.nextInt(password.length);
28            char temp = password[i];
29            password[i] = password[randomPosition];
30            password[randomPosition] = temp;
31        }
32
33        return new String(password);
34    }
35
36    public static void main(String[] args) {
37        for (int i = 0; i < 100; i++) {
38            System.out.println(getPassword(8));
39        }
40    }
41}
42