How can I create a password?

前端 未结 10 1766
悲&欢浪女
悲&欢浪女 2020-12-14 04:37

I want to give maybe a million password to some users that should be like:

  1. It must have at least 6 characters
  2. It must have digits and also letters
10条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 05:17

    A bit late, but I usually use the following code:

    private static final int PASSWORD_SIZE = 16;
    private static final String VALID_SPECIAL_CHARACTERS = "!@#$%&*()_-+=[]{}\\|:/?.,><"; // Note the double \ as escape
    
    private static String createPassword() {
        SecureRandom random = new SecureRandom();
        StringBuilder password = new StringBuilder();
        while (password.length() < PASSWORD_SIZE) {
            char character = (char) random.nextInt(Character.MAX_VALUE);
            if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || (character >= '0' && character <= '9') || VALID_SPECIAL_CHARACTERS.contains(String.valueOf(character))) {
                password.append(character);
            }
        }
        return password.toString();
    }
    

    There is no guarantee that there will always be a number, special character, lower-case and upper-case character in the password. This could be enforced by first adding a character and a digit, however this would create passwords that are a bit more predictable.

提交回复
热议问题