ljacqu b8e2f5fe1d Use RandomString for IPB4 implementation; minor documentation
- Improve RandomString and create new generateLowerUpper method
- Add documentation to the IPB4 class to explain why the salt is stored twice
2016-02-10 21:16:12 +01:00

63 lines
2.0 KiB
Java

package fr.xephi.authme.security;
import java.security.SecureRandom;
import java.util.Random;
/**
* Utility for generating random strings.
*/
public final class RandomString {
private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Random RANDOM = new SecureRandom();
private static final int HEX_MAX_INDEX = 16;
private static final int LOWER_ALPHANUMERIC_INDEX = 36;
private RandomString() {
}
/**
* Generate a string of the given length consisting of random characters within the range [0-9a-z].
*
* @param length The length of the random string to generate
* @return The random string
*/
public static String generate(int length) {
return generate(length, LOWER_ALPHANUMERIC_INDEX);
}
/**
* Generate a random hexadecimal string of the given length. In other words, the generated string
* contains characters only within the range [0-9a-f].
*
* @param length The length of the random string to generate
* @return The random hexadecimal string
*/
public static String generateHex(int length) {
return generate(length, HEX_MAX_INDEX);
}
/**
* Generate a random string with digits and lowercase and uppercase letters. The result of this
* method matches the pattern [0-9a-zA-Z].
*
* @param length The length of the random string to generate
* @return The random string
*/
public static String generateLowerUpper(int length) {
return generate(length, CHARS.length());
}
private static String generate(int length, int maxIndex) {
if (length < 0) {
throw new IllegalArgumentException("Length must be positive but was " + length);
}
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; ++i) {
sb.append(CHARS.charAt(RANDOM.nextInt(maxIndex)));
}
return sb.toString();
}
}