commons-lang icon indicating copy to clipboard operation
commons-lang copied to clipboard

RandomStringUtils.random() does not strictly validate start/end when chars != null, causing potential IndexOutOfBoundsException

Open IcoreE opened this issue 1 month ago • 1 comments

# 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

IcoreE avatar Dec 09 '25 15:12 IcoreE

Hi maintainers,

I have prepared a fix to the problem of the method RandomStringUtils.random(), that:

  1. Adds proper validation to ensure start < chars.length and end <= chars.length.

  2. Throws an IllegalArgumentException when the bounds are invalid.

  3. 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

theodoral22 avatar Dec 12 '25 21:12 theodoral22

Hello @theodoral22 Thank you for your attention to this issue. I have submitted the code and unit tests to fix it. PR#1521

IcoreE avatar Dec 21 '25 07:12 IcoreE

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!

IcoreE avatar Dec 21 '25 15:12 IcoreE

Hello @IcoreE There are higher priority issue I want to deal with.

garydgregory avatar Dec 21 '25 15:12 garydgregory