From b7780a58b8978d84e10e77960b8d68318ff3272c Mon Sep 17 00:00:00 2001 From: theod Date: Sun, 14 Dec 2025 12:53:48 +0200 Subject: [PATCH] Fix RandomStringUtils.random bounds validation This fixes an issue where start/end were not strictly validated when chars is not null, potentially causing IndexOutOfBoundsException. --- .../commons/lang3/RandomStringUtils.java | 13 ++++++++++ .../commons/lang3/RandomStringUtilsTest.java | 24 +++++++++++++++---- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java index 558fc524242..2dd88ed6546 100644 --- a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java +++ b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java @@ -264,6 +264,19 @@ public static String random(int count, int start, int end, final boolean letters throw new IllegalArgumentException("The chars array must not be empty"); } + if (chars!=null) { + if (start>=chars.length) { + throw new IllegalArgumentException( + "Parameter start (" +start+ ") must be less than chars.length ("+chars.length+")" + ); + } + if (end>chars.length) { + throw new IllegalArgumentException( + "Parameter end ("+end+") must be less than or equal to chars.length ("+chars.length+")" + ); + } + } + if (start == 0 && end == 0) { if (chars != null) { end = chars.length; diff --git a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java index 3602fbc6461..b923ee4a8cf 100644 --- a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java @@ -17,11 +17,7 @@ package org.apache.commons.lang3; import static org.apache.commons.lang3.LangAssertions.assertIllegalArgumentException; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -815,4 +811,22 @@ void testRandomWithChars(final RandomStringUtils rsu) { assertNotEquals(r1, r3); assertNotEquals(r2, r3); } + + @Test + void testStartEndOutOfRangeWithChars_shouldThrow() { + final char[] chars = { 'a', 'b', 'c' }; + final Random random = new Random(); + IllegalArgumentException ex; + + ex=assertThrows(IllegalArgumentException.class, () -> + RandomStringUtils.random(5,5,10,false,false,chars,random) + ); + System.out.println("Caught exception: " + ex.getMessage()); + + ex=assertThrows(IllegalArgumentException.class, () -> + RandomStringUtils.random(5,0,5,false,false,chars,random) + ); + System.out.println("Caught exception: " + ex.getMessage()); + } + }