1
0
Fork 0
mirror of https://codeberg.org/Mercury-IM/Smack synced 2024-11-22 14:22:05 +01:00

Remove duplicate code in StringUtils

This commit is contained in:
Florian Schmaus 2017-11-16 18:02:02 +01:00
parent 73dd46af21
commit 2341bb4e23

View file

@ -301,17 +301,7 @@ public class StringUtils {
* @return a random String of numbers and letters of the specified length. * @return a random String of numbers and letters of the specified length.
*/ */
public static String insecureRandomString(int length) { public static String insecureRandomString(int length) {
if (length < 1) { return randomString(length, randGen.get());
return null;
}
final Random random = randGen.get();
// Create a char buffer to put random letters and numbers in.
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[random.nextInt(numbersAndLetters.length)];
}
return new String(randBuffer);
} }
private static final ThreadLocal<SecureRandom> SECURE_RANDOM = new ThreadLocal<SecureRandom>() { private static final ThreadLocal<SecureRandom> SECURE_RANDOM = new ThreadLocal<SecureRandom>() {
@ -322,12 +312,16 @@ public class StringUtils {
}; };
public static String randomString(final int length) { public static String randomString(final int length) {
return randomString(length, SECURE_RANDOM.get());
}
private static String randomString(final int length, Random random) {
if (length < 1) { if (length < 1) {
return null; return null;
} }
byte[] randomBytes = new byte[length]; byte[] randomBytes = new byte[length];
SECURE_RANDOM.get().nextBytes(randomBytes); random.nextBytes(randomBytes);
char[] randomChars = new char[length]; char[] randomChars = new char[length];
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
randomChars[i] = getPrintableChar(randomBytes[i]); randomChars[i] = getPrintableChar(randomBytes[i]);