RandomStringUtils.random() does not strictly validate start/end when chars != null, causing potential IndexOutOfBoundsException
# source code
public static String random(int count, int start, int end, final boolean letters, final boolean numbers,
final char[] chars, final Random random) {
When a custom character array (chars != null) is supplied to RandomStringUtils.random(), the method does not strictly check that the start and end parameters fall within the valid bounds of the chars array.
As a result, if start or end exceeds chars.length, the method may generate a random index outside the array range, leading to an unexpected ArrayIndexOutOfBoundsException.
This fails the method contract and causes unpredictable runtime errors.
@Test
void testStartEndOutOfRangeWithChars() {
char[] chars = {'a', 'b', 'c'};
assertThrows(ArrayIndexOutOfBoundsException.class, () -> {
RandomStringUtils.random(
5,
5, // invalid: start > chars.length
10, // invalid: end > chars.length
false,
false,
chars,
new Random()
);
});
}
Actual: Throws ArrayIndexOutOfBoundsException
Expected: Throw IllegalArgumentException indicating invalid start/end range when chars != null my issue @garydgregory
Hi maintainers,
I have prepared a fix to the problem of the method RandomStringUtils.random(), that:
-
Adds proper validation to ensure start < chars.length and end <= chars.length.
-
Throws an IllegalArgumentException when the bounds are invalid.
-
Includes unit tests to cover these cases.
Would you be open to accepting a pull request with this fix?
Thank you for your time and for maintaining this excellent library!
Best regards, Theodora Anastasia Lazaridou
Hello @theodoral22 Thank you for your attention to this issue. I have submitted the code and unit tests to fix it. PR#1521
Hi @garydgregory I hope everything is going well on your end! It’s been a little while since I submitted PR (#1521), and I just wanted to follow up in case you’ve had a chance to take a look. If you have any feedback or if there’s anything I can improve, I’d be happy to make the necessary changes. Thanks again for all the work you put into the project!
Hello @IcoreE There are higher priority issue I want to deal with.