How can I create a password?

2019-01-22 09:12发布

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

Should I use Random here? How?

10条回答
聊天终结者
2楼-- · 2019-01-22 10:01

When using Apache's RandomStringUtils for security reasons (i.e. passwords), it's very important to combine the use of a SecureRandom source:

RandomStringUtils.random(6, 0, 0, true, true, null, new SecureRandom());
查看更多
一夜七次
3楼-- · 2019-01-22 10:07

Use SecureRandom, it provides a more random passwords.

You can create a single password using something like this (note: untested code).

// put here all characters that are allowed in password
char[] allowedCharacters = {'a','b','c','1','2','3','4'};

SecureRandom random = new SecureRandom();
StringBuffer password = new StringBuffer();

for(int i = 0; i < PASSWORD_LENGTH; i++) {
    password.append(allowedCharacters[ random.nextInt(allowedCharacters.length) ]);
}

Note that this does not guarantee that the every password will have both digits and characters.

查看更多
一夜七次
4楼-- · 2019-01-22 10:08

RandomStringUtils from Apache Commons Lang provide some methods to generate a randomized String, that can be used as password.


Here are some examples of 8-characters passwords creation:

// Passwords with only alphabetic characters.
for (int i = 0; i < 8; i++) {
    System.out.println(RandomStringUtils.randomAlphabetic(8));
}
System.out.println("--------");
// Passwords with alphabetic and numeric characters.
for (int i = 0; i < 8; i++) {
    System.out.println(RandomStringUtils.randomAlphanumeric(8));
}

which creates the following result:

zXHzaLdG
oDtlFDdf
bqPbXVfq
tzQUWuxU
qBHBRKQP
uBLwSvnt
gzBcTnIm
yTUgXlCc
--------
khDzEFD2
cHz1p6yJ
3loXcBau
F6NJAQr7
PyfN079I
8tJye7bu
phfwpY6y
62q27YRt

Of course, you have also methods that may restrict the set of characters allowed for the password generation:

for (int i = 0; i < 8; i++) {
    System.out.println(RandomStringUtils.random(8, "abcDEF123"));
}

will create only passwords with the characters a, b, c, D, E, F, 1, 2 or 3:

D13DD1Eb
cac1Dac2
FE1bD2DE
2ab3Fb3D
213cFEFD
3c2FEDDF
FDbFcc1E
b2cD1c11
查看更多
SAY GOODBYE
5楼-- · 2019-01-22 10:10

What I would do is something like this:

  1. Create two arrays, one with the allowed letters and other with the allowed digits.
  2. Use Random to decide the length of the password.
  3. Use Random to decide whether the next character is a letter or a digit.
  4. Use Random once more to generate an index for the array of letters or digits (depending on wht you obtained in step 3). Append the obtained character to the password.
  5. Repeat from 3 until you have the amount of characters obtained in 2.
查看更多
登录 后发表回答