From 695342cb1cef42f30fd1a8496f181c92b21ae82d Mon Sep 17 00:00:00 2001 From: Ivan Morozov Date: Tue, 15 Nov 2016 11:49:11 +0100 Subject: [PATCH] LANG-1287: RandomStringUtils#random can enter infinite loop if end parameter is to small (closes #211) 1.) Fixed possible infinite loop that can be caused by generating either digits or letters by calling with a to low end param. 2.) Added (inclusive) and (exclusive) terms to javadoc of random method --- .../apache/commons/lang3/RandomStringUtils.java | 15 +++++++++++++-- .../commons/lang3/RandomStringUtilsTest.java | 8 ++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java index 84b30fd64..b76e2695e 100644 --- a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java +++ b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java @@ -327,8 +327,8 @@ public class RandomStringUtils { * and predictably.

* * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before + * @param start the position in set of chars to start at (inclusive) + * @param end the position in set of chars to end before (exclusive) * @param letters only allow letters? * @param numbers only allow numbers? * @param chars the set of chars to choose randoms from, must not be empty. @@ -368,6 +368,17 @@ public class RandomStringUtils { } } + final int zero_digit_ascii = 48; + final int first_letter_ascii = 65; + + if (chars == null) { + if (numbers && end <= zero_digit_ascii + || letters && end <= first_letter_ascii) { + throw new IllegalArgumentException("Parameter end (" + end + ") must be greater then (" + zero_digit_ascii + ") for generating digits " + + "or greater then (" + first_letter_ascii + ") for generating letters."); + } + } + final char[] buffer = new char[count]; final int gap = end - start; diff --git a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java index 28c014b87..4aff749f7 100644 --- a/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/RandomStringUtilsTest.java @@ -206,6 +206,14 @@ public class RandomStringUtilsTest { RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()); fail(); } catch (final IllegalArgumentException ex) {} + try { + RandomStringUtils.random(8, 32, 48, false, true); + fail(); + } catch (final IllegalArgumentException ex) {} + try { + RandomStringUtils.random(8, 32, 65, true, false); + fail(); + } catch (final IllegalArgumentException ex) {} } /**